关于前后端的跨域问题

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.
  1. 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中间件

  1. 安装cors
    cnpm i cors -D
  2. 导入
    const cors = requrie(‘cors’)
    app.use(cors)
  3. 直接在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方式的请求头
}))
  1. 反向代理服务跨域
    0: 什么叫反向代理?
    反向代理指的是在前端的服务器环境中, 短暂的开启一个后端服务器, 由后端服务器进行数据请求, 然后在将结果返回给前端
  2. 使用工程化工具自带的 反向代理服务 — 暂时不能用
    gulp
    webpack (自带的)
  3. 使用第三方提供的反向代理服务 --> 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
})
]
}))
})
  1. 总结:
  2. 后端解决跨域(设置请求头)
  3. express 原生
  4. cors中间件
  5. 前端解决跨域
  6. 反向代理(无论是自带的还是第三方的都得通过工程化工具解决)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值