Access to XMLHttpRequest at 'http://localhost:3000/login' from origin 'http://localhost:9001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- jsonp jsonp + Node.js
1.5 Node.js express跨域
router.get('/shopcar',function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE");
res.header("Access-Control-Allow-Headers", req.header('access-control-request-headers'));
res.render('shopcar',{
goods: '商品1'
})
})
2. cors中间件跨域(两种写法)
1. 全局放置 (能跨域 , 但是接口有问题 ---> 中间件至上而下执行, 匹配成功, 它就停留了)
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中间件
- 安装cors
cnpm i cors -D - 导入
const cors = requrie(‘cors’)
app.use(cors) - 直接在cors中书写配置项 ( 推荐 )
app.use(cors({
origin: ["http://localhost:8001","http://localhost:5000","http://localhost:8080","http://localhost:9001"], //允许所有前端域名
methods: "GET,HEAD,PUT,PATCH,POST,DELETE", //被允许的提交方式
allowedHeaders:['Content-Type','Authorization']//被允许的post方式的请求头
}))
- 反向代理服务跨域
0: 什么叫反向代理?
反向代理指的是在前端的服务器环境中, 短暂的开启一个后端服务器, 由后端服务器进行数据请求, 然后在将结果返回给前端 - 使用工程化工具自带的 反向代理服务 — 暂时不能用
gulp
webpack (自带的) - 使用第三方提供的反向代理服务 --> http-proxy-middleware
// 1. 启动一个静态服务器
gulp.task('server',function(){
gulp.src('./')
.pipe(server({
port: 9001,
host: 'localhost',
livereload: true,
// directoryListing: {
// enable: true,
// path: '/'
// },
open: true,
allowEmpty: true,
middleware: [
// proxy(标记,配置项)
proxy('/yyb',{
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/yyb':''
}
}),
proxy('/login',{
target: 'http://localhost:3000',
changeOrigin: true
})
]
}))
})
- 总结:
- 后端解决跨域(设置请求头)
- express 原生
- cors中间件
- 前端解决跨域
- 反向代理(无论是自带的还是第三方的都得通过工程化工具解决)