-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第56天 JSONP的原理是什么?解决什么问题? #221
Comments
JS 动态插入 script 并将 src 指向后端 API,后台返回 json 并使用协定的 callback 函数把 json 包起来。浏览器以 JS 内容解析执行返回的内容,回调函数得以被调用并传入了返回的 json 对象。 解决的是第一版 XHR 无法发送跨域请求的问题,虽然曾经一度被大厂使用,但是 hack 痕迹满满,并且不支持 post 请求。XHR 2.0 以及 Fetch API 如今兼容性都不错,他们支持 CORS HTTP headers,是跨域资源共享的官方解决方案。 |
原理: 动态插入script标签,执行callback回调函数,将回调函数中的参数输出 解决: 解决跨越问题 缺点: 不支持post 解决跨域方案:
|
解决跨域
function JSONP(url, params, callback) {
const script = document.createElement("script");
script.src = url + parseObjToParams({...params, callback: "jsonpCallback"});
document.body.appendChild(script);
window.jsonpCallback = callback;
script.onload = () => {
document.body.removeChild(script)
}
}
JSONP("http://localhost:3019/asd", {name: "vijay"}, (data) => {
console.log(data);
});
//server
app.use("/asd", (req, res, next) => {
res.jsonp({ user: 'tobi' })
}); |
JSONP的原理一句话来讲: script 引用的js文件没有跨域限制。 可以用来解决跨域问题,兼容性特别好,一般用于给第三方做接口查询。 |
|
jsonP是利用script能够访问任何域名的特性,利用挂载全局的回调函数,可以解决跨域问题。 |
利用 script 标签 src 属性并不被同源策略所约束,可以请求不同域名下的接口。 |
第56天 JSONP的原理是什么?解决什么问题?
The text was updated successfully, but these errors were encountered: