Angular 7 应用程序从 Angular 客户端获取 CORS 错误 [英] Angular 7 app getting CORS error from angular client

查看:26
本文介绍了Angular 7 应用程序从 Angular 客户端获取 CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个带有快速后端的 angular 7 应用程序.Express 在 localhost:3000 上运行,angular 客户端在 localhost:4200 上运行.

I have developed an angular 7 app with express backend. Express running on localhost:3000 and angular client is running on localhost:4200.

server.js 我有(不是整个代码)

In the server.js I have (not the entire code)

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'));

在 api.js 文件中,我有 router.get('/oauth2/login') 重定向到 https://example.com 发送访问令牌并对用户进行身份验证(OAuth2 身份验证).

In the api.js file, I have router.get(‘/oauth2/login’) which redirects to https://example.com which sends an access token and authenticates the user (OAuth2 authentication).

当我调用 url 时 http://localhost:3000/api/oauth2/login 一切正常,但是当我尝试从 angular component.ts -> service.ts 执行相同操作时,出现以下错误.

When I am calling the url http://localhost:3000/api/oauth2/login everything is working fine, but when I am trying to do the same from angular component.ts -> service.ts I am getting the following error.

跨域请求被阻止:同源策略不允许读取远程资源原因:CORS 标头Access-Control-Allow-Origin"失踪

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource Reason: CORS header ‘Access-Control-Allow-Origin’ missing

Angular 应用流程如下 login.component.ts,其中有一个按钮调用服务 api.service.ts,该服务执行 http get.

Angular app flow as follows login.component.ts which has a button calling a service api.service.ts which executes a 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 ));
}

有人能帮我解决这个错误吗?我有 a) CORS b) 将 server.js 中的静态文件作为

Can someone help me get past the error? I have a) CORS b) serving static files from server.js as

app.use(express.static(__dirname + '/dist/sfdc-event'));

c) 动态环境变量.我还缺少什么?

c) dynamic environment variable. What else I am missing?

推荐答案

对于 Angular 7,您必须进行其他实现.从 angular 文档中,您必须创建一个 proxy.js 文件:

For Angular 7 you must do other implementation. From angular documentation you must create a proxy.js file:

https://angular.io/guide/build#using-corporate-proxy

编辑您自己的后端服务器的路径.

Edit the path for your own backend server.

proxy.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);

稍后将此添加到您的 package.json

Later add this to your package.json

"start": "ng serve --proxy-config proxy.js"

并调用它:

npm start

在你的 app.js 中简单地添加:

And in your app.js just simply add:

const cors = require("cors");
app.use(cors());

我遇到了同样的问题,这解决了我的问题.希望能帮到你!

I had same problem and that solved my issue. I hope it helps!

这篇关于Angular 7 应用程序从 Angular 客户端获取 CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆