express 跨域

目标:express   实现跨域;

前提:在服务端执行npm install cors;

方法一:

在app.js:

var cors = require( "cors");

app. use( cors());

app. all( '*', function( req, res, next) {
// res.header("Access-Control-Allow-Credentials","true");
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");//或者 res.header("Access-Control-Allow-Origin", "http://127.0.0.1:3333"); 就只允许 127.0.0.1:3333来访问
res. setHeader( "Access-Control-Allow-Origin", "*");
res. setHeader( "Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res. setHeader( "Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res. setHeader( "X-Powered-By", ' 3.2.1');
if( req. method== "OPTIONS") res. send( 200); /*让options请求快速返回*/
else next();
});

然后,前台在调用时,接口要完整,例如http://localhost:3000/goods/list;

方法二:

可在根目录下,新建文件proxy.config.json,写入以下代码:

{
"/api": {
"target": "http://localhost:3003",
"secure": false,
"pathRewrite": { "/api" : ""}
}
}
,然后在package.json中,添加红色部分:
"scripts": {
"ng": "ng",
"start" : "ng serve --proxy-config proxy.config.json " ,
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},

说明:以上只是以快速实现为主,因为是平时自己做demo用,所以没有考虑到诸如兼容性的问题。实际项目中,需要完善。另外,网上有很多讲述原理的资料,可自行参考;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值