目标: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" :
""}
}
}
"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用,所以没有考虑到诸如兼容性的问题。实际项目中,需要完善。另外,网上有很多讲述原理的资料,可自行参考;