如何为 angular 5/nodejs 启用 Access-Control-Allow-Origin?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50607264/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:49:18  来源:igfitidea点击:

How to enable Access-Control-Allow-Origin for angular 5/nodejs?

node.jsangularhttpangular5webpack-dev-server

提问by aaaaaaaaax10

Read many ways for including of 'Access-Control-Allow-Origin' and none worked for me.

阅读包括“访问控制允许来源”在内的多种方法,但没有一种对我有用。

I use @angular/common/http module and external url as data source. by the attempt to get data instead, get error: /////.................

我使用 @angular/common/http 模块和外部 url 作为数据源。通过尝试获取数据,得到错误://////.................

Failed to load http://accounts.......com/accounts: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 503.


account.service.ts:


account.service.ts:

import { Injectable                    } from '@angular/core';
import { Router                        } from '@angular/router';
import { HttpClient, HttpParams        } from '@angular/common/http';
import { HttpHeaders                   } from '@angular/common/http';

import { Observable                    } from 'rxjs';
import { catchError                    } from 'rxjs/operators';

import { Account                       } from '../models/account';

const baseUrl     : string = 'http://accounts..................com/';
const httpOptions : any    = {
  headers: new HttpHeaders({
    //'Content-Type':  'application/json',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Allow-Origin': '*'
  })
};

@Injectable()
export class AccountService {
  private isUserLoggedIn;
  private usreName;
  private account : Account;

  constructor(
    private http: HttpClient,
    private router: Router
  ) {}

  logIn (credentials: any): Observable<Account> {
    return this.http.get<Account>(baseUrl + 'accounts');
  }
}

app.module.ts

app.module.ts

import { BrowserModule                 } from '@angular/platform-browser';
import { HttpClientModule              } from '@angular/common/http';
import { NgModule                      } from '@angular/core';

import { routing                       } from './routing';
import { AppComponent                  } from './app.component';
import { AppGlobal                     } from './app.global';

import { AccountComponent              } from './components/account/account.component';

@NgModule({
  declarations  : [
    AppComponent,
    AccountComponent,
    ....
  ],
  imports       : [
    routing,
    BrowserModule,
    HttpClientModule,
    CookieModule.forRoot()
  ],
  providers     : [AccountService, AppGlobal],
  bootstrap     : [AppComponent]
})
export class AppModule { }

Help please

请帮忙

////////////////Tried fix 1

////////////////尝试修复1

//......
import { HttpHeaders} from '@angular/common/http';
//.......
logIn (credentials: any): Observable<Account> {

    const headers = new HttpHeaders()
      .append('Content-Type', 'application/json')
      .append('Access-Control-Allow-Headers', 'Content-Type')
      .append('Access-Control-Allow-Methods', 'GET')
      .append('Access-Control-Allow-Origin', '*');
    return this.http.get<Account>(baseUrl + 'accounts',  {headers});
}
enter image description here在此处输入图片说明

I am still getting that error :

我仍然收到该错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 503.

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:4200'。响应具有 HTTP 状态代码 503。

////////////////Tried fix 2

////////////////尝试修复2

proxy.conf.json:

proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:4200",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

ng serve --proxy-config proxy.conf.json

ng serve --proxy-config proxy.conf.json

also error

还有错误

回答by Vishal Maru

**Set headers to allow CORS origin in Express **

**设置标题以允许 Express 中的 CORS 来源 **

=> Add code in the server.js file or mail file.

=> 在 server.js 文件或邮件文件中添加代码。

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

CORS (Cross-Origin Resource Sharing) is an HTML5 feature that allows one site to access another site's resources despite being under different domain names.

CORS(跨域资源共享)是一项 HTML5 功能,允许一个站点访问另一个站点的资源,尽管它们位于不同的域名下。

The W3C specification for CORS actually does a pretty good job of providing some simple examples of the response headers, such as the key header, Access-Control-Allow-Origin, and other headers that you must use to enable CORS on your web server.

CORS 的 W3C 规范实际上很好地提供了一些简单的响应标头示例,例如密钥标头、Access-Control-Allow-Origin 和其他必须用于在 Web 服务器上启用 CORS 的标头。

回答by ippi

You mentioned webpack-dev-server, which of course can handle CORS since it's using express behind the scenes. In your webpack config

您提到了 webpack-dev-server,它当然可以处理 CORS,因为它在幕后使用 express。在你的 webpack 配置中

devServer: {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
  }
},

回答by Ab Ebube

If you are using .NET Api then add this to your WebApiConfig.cs file

如果您使用的是 .NET Api,请将其添加到您的 WebApiConfig.cs 文件中

    public static void Register(HttpConfiguration config)
    {
        var enableCorsAttribute = new EnableCorsAttribute("*",
                                           "Origin, Content-Type, Accept",
                                           "GET, PUT, POST, DELETE, OPTIONS");
        config.EnableCors(enableCorsAttribute);
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

回答by Ardy Febriansyah

Access-Control-Allow-Origin

Is response header not request header. You must add this header to your resfull (server)

是响应头不是请求头。您必须将此标头添加到 resfull(服务器)