跨域
CORS
原理:服务端设置响应头即可
原生设置响应头
// 原生
res.setHeader("Access-Control-Allow-Origin", "*");
框架 设置响应头
app.all("/*", function(req, res, next) {
// 跨域处理
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next(); // 执行下一个路由
})
框架 使用第三方 cors 包
const cors = require('cors');
//将cors挂载
app.use(cors())
JSNOP
前端
// 封装jsonp函数
function jsonp(options) {
// 动态设置script标签
var script = document.createElement('script');
// 通过地址传值
script.src =options.url;
// 添加到body中
document.body.appendChild(script);
// 当script标签加载完成之后,删除这个script标签
script.onload = function () {
document.body.removeChild(this);
}
}
//调用
jsonp({
url:'http://localhost:3001/better?callback=fn',
})
服务端
// 处理 POST 请求(POST、DELETE...)
getPostData(req).then((postData) => {
// req 添加 body 字段并赋予 postData 数据
req.body = postData;
// 下面所有接口都可以获取到 postData 数据
// 处理 timeline 路由
const timelineData = handleTimelineRouter(req, res);
if (timelineData) {
timelineData.then((data) => {
// 解决浏览器 jsonp 请求
if (req.query && req.query.callback) {
var str = req.query.callback + "(" + JSON.stringify(data) + ")";
res.end(str);
} else {
//普通的json
res.end(JSON.stringify(data));
}
});
return;
}
// 未命中路有,返回 404
res.writeHead(404, { "Content-Type": "text/plain" });
res.write("404 Not Found\n");
res.end();
});