【问题标题】:How to enable Access-Control-Allow-Origin for angular 5/nodejs?如何为 angular 5/nodejs 启用 Access-Control-Allow-Origin?
【发布时间】:2018-11-09 11:04:14
【问题描述】:

阅读包括“Access-Control-Allow-Origin”在内的许多方法,但没有一个对我有用。

我使用 @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});
}

我仍然收到该错误:

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

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

proxy.conf.json:

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

ng 服务 --proxy-config proxy.conf.json

还有错误

【问题讨论】:

  • CORS 应该由您请求资源的服务器启用,而不是来自 Angular。
  • @DavidAnthonyAcosta,Angular2+ 是客户端库,不用于服务器端渲染。我只用,我想应该配置webpack-dev-server
  • 不,webpack 不需要为 CORS 配置。 Angular 我不是一个客户端库,它是一个框架。请参阅下面的 Ab Ebube 的回答。如您所见,他正在配置 cors 服务器端而不是客户端
  • @DavidAnthonyAcosta,我也是用node js,没想到应该配置node js
  • 您使用的任何服务器都需要配置。如果您使用的是 NodeJS 服务器,那么您可以使用名为 CORS 的 npm 包,它可以让您轻松配置它

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


【解决方案1】:

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

CORS 的 W3C 规范实际上很好地提供了一些简单的响应标头示例,例如密钥标头、Access-Control-Allow-Origin 以及您必须使用这些标头才能在您的设备上启用 CORS网络服务器。

【讨论】:

  • 我不使用 ExpressJs
  • 您必须在 API 服务器(开发 API 的地方)上启用 CORS。在哪个服务器 API 上开发?
  • 我为我从未知服务器获取了 API。我只需要使用它
  • 我可以从直接链接 API 获取/查看数据,但不能通过 Angular
  • 您必须告诉 API 开发人员启用 CORS。快乐编码
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    Access-Control-Allow-Origin
    

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 你必须为此安装 nuget packet Microsoft.AspNet.WebApi.Cors
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2017-06-23
      • 2018-12-12
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多