http://xxx/xxx?callback=callbackFunction
callbackFunction(data)
例子:
// 客户端 function usejsonp() { const script = document.createElement("script"); script.src = "http://127.0.0.1:8000/test?callback=jsonp"; script.addEventListener("error", () => { console.log("error"); }); document.body.appendChild(script); } function jsonp(data) { console.log(data); }
// 服务器端 app.get("/test", (req, res) => { const params = new URL(req.url); const data = JSON.stringify({ state: "succeess" }); const reqdata = `${params.query.callback}(${data})`; res.writeHead(200, { "Content-Type": "text/javascript" }); res.end(reqdata); });