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

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

阅读许多对我有用的 'Access-Control-Allow-Origin' 和 none 方法。

我使用@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:

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

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 { }

请帮忙

///////////////已尝试修复 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});
}

我仍然收到该错误:

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.

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

proxy.conf.json:

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

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

也有错误

如果您使用的是 .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 }
        );
    }
}

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

=> 在 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 资源共享)是一项 HTML5 功能,允许一个站点访问另一个站点的资源,尽管它们位于不同的域名下。

CORS 的 W3C 规范实际上做得很好,它提供了一些响应 header 的简单示例,例如键 header、Access-Control-Allow-Origin 和其他 header您必须使用它来在您的 Web 服务器上启用 CORS。

Access-Control-Allow-Origin

是回应header不是请求header。您必须将此 header 添加到您的 resfull(服务器)

您提到了 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"
  }
},