如何在angular中使用代理解决CORS问题 [英] How to resolve the CORS issue using proxy in angular
问题描述
我正在使用Express Node后端和前端进行角度处理.问题是当我将我的API集成到angular时,我遇到了CORS问题.在开发人员控制台中,我遇到了这样的错误:"XmlHttpRequet无法加载 http://localhost:3000/student 没有访问控制-允许起源"
I am using express Node backend and frontend for angular. the thing is when i was integrate my API to angular i had CORS problem. inside the developer console i have got a error like this "XmlHttpRequet cannot load http://localhost:3000/student No Access-Control-Allow-Origin"
我试图代理后端,在angular项目中添加了proxy-confg.json.但结果也一样.仍然有CORS问题.
I have tried to proxy the backend adding a proxy-confg.json inside the angular project. but the result also same. still have CORS problem.
// 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配置
Here the Proxy configuration inside angular project proxy.conf.json
{
"/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文件中.
Add this code in app.js file.
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();
});
然后重新启动服务器.
这篇关于如何在angular中使用代理解决CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!