如何在 angular 中使用代理解决 CORS 问题 [英] How to resolve the CORS issue using proxy in angular
问题描述
我正在使用 express Node 后端和前端来处理 angular.问题是当我将 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)
);
}
这里是angular项目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屋!