What is JSONP?
jsonp is an unofficial cross-domain solution that only supports GET requests.
How does JSONP work?
There are some tags that originally have cross-domain capabilities in the webpage, such as img, link, iframe, script, and jsonp that use the cross-domain capabilities of script tags to send requests.
- Take the script tag as an example, jsonp cannot accept ordinary strings, but js code
Native jsonp cross-domain case
- When the user's focus leaves the input box, send a jsonp request, and then return that the user name already exists, and at the same time change the border color of the input box to red.
- Client:
// 获取input和p标签
const input = document.querySelector('input');
const p = document.querySelector('p');
// 定义handle函数
function handle(data) {
input.style.border = 'solid 2px red';
p.innerHTML = data.msg;
};
// 当用户的焦点移出输入框时触发函数
input.onblur = function() {
// 获取用户输入的值
let user_input = this.value;
// 创建script标签,发送jsonp请求
const script = document.createElement('script');
// 向script标签中添加url
script.src = "http://localhost:9000/jsonp";
// 将创建好的script标签加到文档对象模型中
document.body.appendChild(script);
- Service-Terminal
// 测试jsonp服务
app.all('/jsonp',(request,response) => {
const data = {
id: 1,
msg: '该用户名已存在'
};
const str = JSON.stringify(data);
response.send(`handle(${
str})`);
})