我正在使用Express Node后端和前端进行角度处理。问题是当我将我的API集成到angular时出现了CORS问题。在开发人员控制台内部,我遇到了这样的错误:“ XmlHttpRequet无法加载http://localhost:3000/student No Access-Control-Allow-Origin”
我尝试代理后端,在angular项目内添加proxy-confg.json。但结果也一样。仍然有CORS问题。
// node js endpoint
ApienpointUrl = 'http://localhost:4200/stdApi/student';
// getting data from endpoint
getStudentfromMock() {
return this.http.get(this.ApienpointUrl).pipe(
map((res: any) => res),
catchError(this.handleError)
);
}
这里是角度项目proxy.conf.json中的Proxy配置
{
"/stdApi/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
我遇到这样的错误:-
"XmlHttpRequet cannot load http://localhost:4200/stdApi/student No Access-Control-Allow-Origin. header is present on the request resources origin 'http://localhost:3000' therefor not allowed access".
将此代码添加到app.js文件中。
app.use((req, res, next) => {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, token, language');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
并重新启动服务器。