Angular 7应用程序从Angular客户端获取CORS错误

Aru*_*kar 8 node.js cors express angular angular7

我开发了一个带有后端的angular 7应用程序。Express在Angular上运行,localhost:3000而Angular Client在localhost:4200上运行。

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'));
Run Code Online (Sandbox Code Playgroud)

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

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

跨域请求被阻止:同源策略禁止读取远程资源原因:CORS标头“ Access-Control-Allow-Origin”丢失

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 ); });
}
Run Code Online (Sandbox Code Playgroud)

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 ));
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我克服错误吗?我有一个)CORS b)从server.js提供静态文件作为

app.use(express.static(__dirname + '/dist/sfdc-event'));
Run Code Online (Sandbox Code Playgroud)

c)动态环境变量。我还想念什么?

Fre*_*e09 6

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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

"start": "ng serve --proxy-config proxy.js"
Run Code Online (Sandbox Code Playgroud)

并使用以下命令调用:

npm start
Run Code Online (Sandbox Code Playgroud)

在您的app.js中,只需添加:

const cors = require("cors");
app.use(cors());
Run Code Online (Sandbox Code Playgroud)

我有同样的问题,那解决了我的问题。希望对您有所帮助!


小智 6

To divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api, take the following steps.

  1. Create a file proxy.conf.json in the projects src/ folder, next to package.json.

  2. Add the following content to the new proxy file:

{
    "/api": {
        "target": "`http://localhost:3000`",
        "secure": false
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 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"
        },
    ...
    }
}
...
Run Code Online (Sandbox Code Playgroud)
  1. 要使用此代理配置运行开发服务器,请调用ng serve


pio*_*cki 5

如果这只是为了开发,我建议使用 angular-cli 附带的代理。创建一个名为 proxy.json 的文件

{
  "/api/oauth2/login": {
    "target": "http://localhost:3000/api/oauth2/login",
    "secure": false
  }
}
Run Code Online (Sandbox Code Playgroud)

和电话ng serve --proxy-config proxy.json。如果您认为这仍然是生产中的问题,那么我们必须进行更大的对话。

完整文档:https : //github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

还有什么是 CORS:https : //developer.mozilla.org/en-US/docs/Web/HTTP/CORS


Sad*_*jee -5

由于您的 Angular 应用程序在 4200 端口上运行,后端在 3000 端口上运行,因此两个应用程序的来源不同。

为了解决这个问题,你可以在你的机器上安装“nginx”。

这将使来自角度和后端的所有请求都通过“nginx”服务器进行。这样,就解决了CORS的问题。