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

时间:2018-05-30 14:28:48

标签: node.js angular http angular5 webpack-dev-server

阅读许多方法,包括“访问控制 - 允许 - 来源”和#39;没有人为我工作。

我使用@ 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');
  }
}
&#13;
&#13;
&#13;

app.module.ts

&#13;
&#13;
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 { }
&#13;
&#13;
&#13;

请帮助

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

&#13;
&#13;
//......
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});
}
&#13;
&#13;
&#13; enter image description here

我仍然收到这个错误:

  

对预检请求的响应没有通过访问控制检查:否&#39;访问控制 - 允许 - 来源&#39;标头出现在请求的资源上。起源&#39; http://localhost:4200&#39;因此不允许访问。响应的HTTP状态代码为503。

////////////////试过修理2

proxy.conf.json:

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

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

也是错误

4 个答案:

答案 0 :(得分:4)

在NodeJs / Express Js中允许CORS原点

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

CORS的W3C规范实际上提供了一些响应头的简单示例,例如密钥头​​,Access-Control-Allow-Origin以及必须用于启用CORS的其他头的其他头文件。网络服务器。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

Access-Control-Allow-Origin

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

答案 3 :(得分:0)

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