[英]Angular 6 HttpClient - Issues with CORS
My Nodejs restful service has the following endpoint http://localhost:3000/api/countries .我的 Nodejs 宁静服务具有以下端点http://localhost:3000/api/countries 。 I am using this middleware https://github.com/expressjs/cors .
我正在使用这个中间件https://github.com/expressjs/cors 。 I have cors enabled thus:-
我因此启用了 cors:-
const cors = require('cors');
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
I have the following code in my Angular 6 app hosted at http://localhost:4200我在http://localhost:4200托管的 Angular 6 应用程序中有以下代码
import { HttpClient, HttpHeaders } from '@angular/common/http';
httpClient: HttpClient;
getCountries(): Observable<any> {
const url = 'http://localhost:3000/api/countries';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
})
};
return this.httpClient.get(url, httpOptions).pipe(
map((result: any) => {
return result;
})
);
}
I have the following code in my React App at http://localhost:3001我的 React App 中有以下代码,地址为http://localhost:3001
getCountries() {
const url = 'http://localhost:3000/api/countries';
const init = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
try {
const response = await fetch(url, init);
const json = await response.json();
return json
};
}
My react code works perfectly giving the desired response, but the Angular 6 gives the following error:-我的反应代码完美地给出了所需的响应,但 Angular 6 给出了以下错误:-
Access to XMLHttpRequest at ' http://localhost:3000/api/countries ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
访问 XMLHttpRequest at ' http://localhost:3000/api/countries ' from origin ' http://localhost:4200 ' 已被 CORS 策略阻止:请求头字段 access-control-allow-origin is not allowed by Access -Control-Allow-Headers 在预检响应中。
What am I doing wrong in my angular 6 code?我在 angular 6 代码中做错了什么?
Please note that I have seen answers to similar questions suggesting using a json file (proxy.conf.json) to act as a proxy server or install a chrome extension.请注意,我已经看到类似问题的答案,建议使用 json 文件 (proxy.conf.json) 作为代理服务器或安装 chrome 扩展。 These are not options for me.
这些都不是我的选择。
Thanks in advance of your helpful responses.提前感谢您的有用回复。
如果您想要一个快速的临时解决方案,您可以使用它。
const url = 'https://cors-anywhere.herokuapp.com/http://localhost:3000/api/countries';
The CORS is mostly a backend issue. CORS 主要是后端问题。 You can solve it on Node.js with a code such as:
您可以使用以下代码在 Node.js 上解决它:
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
But if you want to solve it in frontend, you may use this kind of code in Angular.但是如果你想在前端解决它,你可以在Angular中使用这种代码。 Put this code into a proxy.conf.json (but beware, a trailing slash is enough to make it not to work):
将此代码放入 proxy.conf.json (但请注意,尾部斜杠足以使其不起作用):
{
"/api/*": { <-- you may change this for /api/country
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
The following in package.json: package.json 中的以下内容:
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
...
}
And add the proxy config in angular.json:并在 angular.json 中添加代理配置:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "event:build",
"proxyConfig": "proxy.conf.json" <-- this line
},...
Start it with npm start
.使用
npm start
启动它。
It should work in your case, but in other cases (not in prod of course), I find it easier to use temporarily an extension for Chrome or Firefox .它应该适用于您的情况,但在其他情况下(当然不是在产品中),我发现暂时使用Chrome或Firefox的扩展程序更容易。 Also I found that because of some restriction it may not work in Chromium and Chrome Canary.
我还发现由于某些限制,它可能无法在 Chromium 和 Chrome Canary 中运行。
Additionally with React the following code may help:此外,对于 React,以下代码可能会有所帮助:
const proxy = require("http-proxy-middleware");
module.exports = app => {
app.use(
"/api", <-- here again, make sure it fits your needs or it won't work
proxy({
target: "http://localhost:3000",
changeOrigin: true
})
);
};
Try using ng serve --port 3000 .尝试使用 ng serve --port 3000 。 The CORS is mostly backend issue.
CORS 主要是后端问题。 Since react starts it's server in localhost:3000 you were able to consume it, since angular starts in localhost:4200 you got the cors issue.
由于 react 在 localhost:3000 中启动它的服务器,因此您可以使用它,因为 angular 在 localhost:4200 中启动,因此您遇到了 cors 问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.