background
Recently, I met the company’s preference for JSONP back-end. I didn’t succeed in the first time when I was in synch, but it took some time when I encountered an error. So I wrote it by myself to deepen my understanding.
Think of a poem, write it down
"Winter night reading shows the son yu" Lu You the ancient knowledge without exhaustion, young time old beginning. The paper come zhongjue shallow, and must know this to practice.Copy the code
JS request part
The principle is to use script Link imgsrc data across domains, with the convention callback, passing the requested data using parameters.
const options = {
callbackName: 'callback'
}
function jsonp({ url, params, callback }) {
return new Promise((resolve, reject) = > {
let script = document.createElement('script');
params = JSON.parse(JSON.stringify(params));
const arr = [];
for (const key in params) {
arr.push(`${key}=${params[key]}`);
}
arr.push(`callback=${callback}`);
script.src = `${url}?${arr.join('&')}`;
document.body.append(script);
window[options.callbackName] = function(data) {
delete window[options.callbackName];
resolve(data);
document.body.removeChild(script);
};
});
}
jsonp({
url: 'http://127.0.0.1:7001/jsonp'.params: {
word: 'i love you',},callback: 'callback'
}).then(data= > {
console.log(data)
});
Copy the code
An Egg. Js json
router.js
There is JSONP middleware, which has the advantage of returning JSON directly without the need to concatenate callback function calls
module.exports = app= > {
const { router, controller } = app;
const jsonp = app.jsonp();
router.get('/', controller.home.index);
router.get('/jsonp', jsonp, controller.home.jsonpTest);
};
Copy the code
controller
async jsonpTest() {
const { ctx } = this;
const {callback,wd} = ctx.query;
console.log(callback, wd);
let data = {
username: 'test'.password: '123123'}; ctx.body = data; }Copy the code
Express.js
No middleware needs to splice callbacks
const express = require('express')
const app = express()
const port = 3000
var router = express.Router();
app.get('/', (req, res) => res.send('Hello World! '))
app.get('/jsonp'.function(req, res, next) {
let data = {
username : 'www.fire1024.com'.password : 123456
}
// Call the callback function and respond
res.send(`${callback}(The ${JSON.stringify(data)}) `);
})
app.listen(port, () => console.log(`Example app listening on port ${port}! `))
Copy the code