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