Angular 6 HttpClient - CORS 问题 [英] Angular 6 HttpClient - Issues with CORS

查看:35
本文介绍了Angular 6 HttpClient - CORS 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Nodejs 宁静服务具有以下端点 http://localhost:3000/api/countries.我正在使用这个中间件 https://github.com/expressjs/cors.我因此启用了 cors:-

My Nodejs restful service has the following endpoint http://localhost:3000/api/countries. I am using this middleware https://github.com/expressjs/cors. I have cors enabled thus:-

const cors = require('cors');
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

我在 http://localhost:4200

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

我的 React 应用程序中有以下代码,位于 http://localhost:3001

I have the following code in my React App at 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
   };
 }

我的反应代码完美地给出了所需的响应,但 Angular 6 给出了以下错误:-

My react code works perfectly giving the desired response, but the Angular 6 gives the following error:-

访问 XMLHttpRequest 在 'http://localhost:3000/api/countries' 来自来源 'http://localhost:4200' 已被 CORS 政策阻止:请求头字段 access-control-allow-origin 不允许预检响应中的 Access-Control-Allow-Headers.

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.

我的 angular 6 代码做错了什么?

What am I doing wrong in my angular 6 code?

请注意,我已经看到类似问题的答案建议使用一个 json 文件 (proxy.conf.json) 作为代理服务器或安装 chrome 扩展.这些都不是我的选择.

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. These are not options for me.

预先感谢您的有用回复.

Thanks in advance of your helpful responses.

推荐答案

您可以使用 this 如果您想要一个快速的临时解决方案.

You can use this if you want a quick temporary solution.

const url = 'https://cors-anywhere.herokuapp.com/http://localhost:3000/api/countries';

这篇关于Angular 6 HttpClient - CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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