Jsonp cross-domain error report

Front

$.ajax({
    type: "GET",
    url: "localhost:3000/getData.jsonp",
    dataType: "jsonp",
    success: function(data) {
      console.log(data)
    }
});

node

const Koa = require("koa")
const app = new Koa()
app.use(async(ctx) => {
    console.log(ctx.method);
    ctx.set("Access-Control-Allow-Origin", "*");
    /**/
    ctx.set("Access-Control-Allow-Methods", "GET,POST");
    // jsonp GET
    if (ctx.method === "GET" && ctx.url.split("?")[0] === "/getData.jsonp") {
        console.log(ctx.query)
        // jsonpcallback
        let callbackName = ctx.query.callback || "callback"
        let returnData = {
            success: true,
            data: {
                text: "this is a jsonp api",
                time: new Date().getTime(),
            }
        }
        // jsonpscript
        let jsonpStr = `;${callbackName}(${JSON.stringify(returnData)})`
        // text/javascript
        ctx.type = "text/javascript"
        // jsonp
        ctx.body = jsonpStr
    } else {
        ctx.body = "hello jsonp"
    }
})
app.listen(3000, () => {
    console.log("[demo] jsonp is starting at port 3000")
})

browser access reported an error, and there is no background printing in the console

there is nothing printed on node. I don"t think I got there in node.

Gods, please help

Mar.10,2021

print your jsonpStr and see what it looks like after stitching.


jsonp has no cross-domain problems.


ctx.url.split ('?) [0] ='/ getData.jsonp' can this sentence pass?


there is something wrong with your request method. It is recommended to Google how jsonp requests data

.
Menu