node.js Angular 7 应用程序从 Angular 客户端获取 CORS 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53473754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 7 app getting CORS error from angular client
提问by Arup Sarkar
I have developed an angular 7 app with express backend. Express running on localhost:3000and angular client is running on localhost:4200.
我开发了一个带有快速后端的 angular 7 应用程序。Expresslocalhost:3000在 localhost:4200 上运行,Angular 客户端正在运行。
In the server.jsI have (not the entire code)
在server.js我有(不是整个代码)
const app = express();
// Enable CORS
app.use(cors());
// Get our API routes
const api = require('./api');
// Set our api routes
app.use('/api', api);
app.use(express.static(__dirname + '/dist/sfdc-event'));
In the api.js file, I have router.get(‘/oauth2/login') which redirects to https://example.comwhich sends an access token and authenticates the user (OAuth2 authentication).
在 api.js 文件中,我有 router.get('/oauth2/login') 重定向到https://example.com,它发送访问令牌并验证用户(OAuth2 验证)。
When I am calling the url http://localhost:3000/api/oauth2/logineverything is working fine, but when I am trying to do the same from angular component.ts -> service.ts I am getting the following error.
当我调用 url http://localhost:3000/api/oauth2/login 时,一切正常,但是当我尝试从 angular component.ts -> service.ts 执行相同操作时,出现以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource Reason: CORS header ‘Access-Control-Allow-Origin' missing
跨域请求被阻止:同源策略不允许读取远程资源原因:缺少 CORS 标头“Access-Control-Allow-Origin”
Angular app flow as follows login.component.ts which has a button calling a service api.service.ts which executes a http get.
Angular 应用程序流程如下 login.component.ts,其中有一个按钮调用服务 api.service.ts,该服务执行 http get。
login.component.ts
sfdcLogin(): void {
console.log('DEBUG: LoginComponent: ', 'Login button clicked..');
this.apiService.login().subscribe( data => { console.log( data ); });
}
api.service.ts
api.service.ts
login() {
console.log('DEBUG: APiService login(): ', 'login() function.');
const URL = 'oauth2/login';
console.log('DEBUG: ApiService login URL : ', `${environment.baseUrl}/${URL}`.toString());
return this.http.get(`${environment.baseUrl}/${URL}`)
.pipe( map( res => res ));
}
Can someone help me get past the error? I have a) CORS b) serving static files from server.js as
有人可以帮助我克服错误吗?我有 a) CORS b) 从 server.js 提供静态文件作为
app.use(express.static(__dirname + '/dist/sfdc-event'));
c) dynamic environment variable. What else I am missing?
c) 动态环境变量。我还缺少什么?
回答by Freestyle09
For Angular 7 you must do other implementation. From angular documentation you must create a proxy.js file:
对于 Angular 7,您必须进行其他实现。从 angular 文档中,您必须创建一个 proxy.js 文件:
https://angular.io/guide/build#using-corporate-proxy
https://angular.io/guide/build#using-corporate-proxy
Edit the path for your own backend server.
编辑您自己的后端服务器的路径。
proxy.js:
代理.js:
var HttpsProxyAgent = require('https-proxy-agent');
var proxyConfig = [{
context: '/api',
target: 'http://your-remote-server.com:3000',
secure: false
}];
function setupForCorporateProxy(proxyConfig) {
var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
if (proxyServer) {
var agent = new HttpsProxyAgent(proxyServer);
console.log('Using corporate proxy server: ' + proxyServer);
proxyConfig.forEach(function(entry) {
entry.agent = agent;
});
}
return proxyConfig;
}
module.exports = setupForCorporateProxy(proxyConfig);
Later add this to your package.json
稍后将此添加到您的 package.json
"start": "ng serve --proxy-config proxy.js"
And call this with:
并调用它:
npm start
And in your app.js just simply add:
在你的 app.js 中只需简单地添加:
const cors = require("cors");
app.use(cors());
I had same problem and that solved my issue. I hope it helps!
我有同样的问题,这解决了我的问题。我希望它有帮助!
回答by TiyebM
To divert all calls for http://localhost:4200/apito a server running on http://localhost:3000/api, take the followingsteps.
要将所有呼叫转移http://localhost:4200/api到运行在 上的服务器http://localhost:3000/api,请执行以下步骤。
Create a file proxy.conf.json in the projects src/ folder, next to package.json.
Add the following content to the new proxy file:
{ "/api": { "target": "
http://localhost:3000", "secure": false } }In the CLI configuration file, angular.json, add the proxyConfig option to the serve target:
... "architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-application-name:build", "proxyConfig": "src/proxy.conf.json" }, ...
To run the dev server with this proxy configuration, call ng serve.
在项目 src/ 文件夹中,在 package.json 旁边创建一个文件 proxy.conf.json。
将以下内容添加到新的代理文件中:
{ "/api": { "target": "
http://localhost:3000", "secure": false } }在 CLI 配置文件 angular.json 中,将 proxyConfig 选项添加到服务目标:
...“建筑师”:{“服务”:{“建造者”:“@angular-devkit/build-angular:dev-server”,“选项”:{“浏览器目标”:“你的应用程序名称:构建” , "proxyConfig": "src/proxy.conf.json" }, ...
要使用此代理配置运行开发服务器,请调用 ng serve。
回答by David Q
I have been working with Angular cliand .net Frameworkin server side.
我一直在服务器端使用Angular cli和.net Framework。
To solve this problem, I just ennable CORS interaction in server side using the following steps:
为了解决这个问题,我只是使用以下步骤在服务器端启用 CORS 交互:
Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.6And then, into WebApiConfig class:
Add
using System.Web.Http.Cors;Inside Register(HttpConfiguration config) method:
Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.6然后,进入 WebApiConfig 类:
添加
using System.Web.Http.Cors;内部 Register(HttpConfiguration config) 方法:
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(cors);
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(cors);
or
或者
var cors = new EnableCorsAttribute("*", "*", "*"); //origin, headers, methods config.EnableCors(cors);
var cors = new EnableCorsAttribute("*", "*", "*"); //origin, headers, methods config.EnableCors(cors);
回答by piotr szybicki
If this is just for development I recommend using proxy that comes with angular-cli. Create a file called proxy.json
如果这只是为了开发,我建议使用 angular-cli 附带的代理。创建一个名为 proxy.json 的文件
and
和
{
"/api/oauth2/login": {
"target": "http://localhost:3000/api/oauth2/login",
"secure": false
}
}
and the call ng serve --proxy-config proxy.json. If you expect this to be still a problem in production then we have to have a bigger conversation.
和电话ng serve --proxy-config proxy.json。如果您认为这仍然是生产中的问题,那么我们必须进行更大的对话。
Full documentation: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
完整文档:https: //github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
Also what is CORS exacly: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
还有什么是 CORS:https: //developer.mozilla.org/en-US/docs/Web/HTTP/CORS
回答by Arup Sarkar
I changed the callback mechanism to get past the CORS issue, I am utilizing a OAuth flow for the user to get authenticated from https://example.comwhich was redirecting to https://example.com/auth/callback, I was initiating the request from http://localhost:4200and then sending the callback url to the server http://localhost:3000and I was getting the CORS error.
我更改了回调机制以解决 CORS 问题,我正在利用 OAuth 流让用户从https://example.com进行身份验证,该流重定向到https://example.com/auth/callback,我是从http://localhost:4200发起请求,然后将回调 url 发送到服务器http://localhost:3000,我收到了 CORS 错误。
Now, I am redirecting it to the client http://localhost:4200and got past the CORS problem. All other calls for GET, POST, DELETE, PATCH is from the http://localhost:3000which is working fine.
现在,我将它重定向到客户端http://localhost:4200并解决了 CORS 问题。对 GET、POST、DELETE、PATCH 的所有其他调用都来自http://localhost:3000,它工作正常。
Thank you all for your inputs.
感谢大家的投入。
回答by Ankit21ks
I know this is already answered, but it might help someone who is searching for CORS issue. You can follow below 3 steps to solve this issue. 1. Create proxy.conf.json file and put it at root level of your app. 2. In package.json file, add proxy parameter in ngstart 3. In angular.json, add proxy file entry. 4. Change all your rest calls to something like /api/getData.
我知道这已经得到了回答,但它可能会对正在搜索 CORS 问题的人有所帮助。您可以按照以下 3 个步骤来解决此问题。1. 创建 proxy.conf.json 文件并将其放在应用程序的根级别。2. 在 package.json 文件中,在 ngstart 中添加代理参数 3. 在 angular.json 中,添加代理文件条目。4. 将您所有的其余调用更改为 /api/getData 之类的内容。
Complete step by step tutorial is given here. http://www.codeyourthought.com/angular/proxy-to-make-http-call-in-angular/
此处提供了完整的分步教程。 http://www.codeyourthought.com/angular/proxy-to-make-http-call-in-angular/
回答by Saddam Pojee
Since, your angular app is running on 4200 port and backend running on 3000 port, the origin of both the application is different.
由于您的 angular 应用程序在 4200 端口上运行而后端在 3000 端口上运行,因此这两个应用程序的起源是不同的。
To solve this problem, you can setup "nginx" in your machine.
为了解决这个问题,你可以在你的机器上设置“nginx”。
This will make all your requests from angular and backend, go via "nginx" server. Thus, solving the problem of CORS.
这将使您从 angular 和后端发出所有请求,通过“nginx”服务器。至此,解决了CORS的问题。

