访问WebApi

时间:2018-05-03 07:50:04

标签: angular http asp.net-web-api

我有这项服务:

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

@Injectable()
export class LoginService {

  constructor(private http: HttpClient) {}

  getUsers() {
    const options = {
        headers: new HttpHeaders({
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': 'Origin, Content-Type',
          'Content-Type': 'text/xml'
        })
      };

    return this.http.get('myurl', options);
  }
}

我正在尝试访问只有GET的API。此特定资源允许匿名访问。

但是,我收到以下错误(在Chrome控制台中):

  

选项myurl 405(方法不允许)

     

无法加载myurl:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://localhost:4200'因此不允许访问。响应的HTTP状态代码为405。

有关如何解决这些错误的任何想法?

3 个答案:

答案 0 :(得分:1)

假设您是dotnet核心。

取自MSFT Docs:你需要在Startup.cs中允许使用CORS:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
       builder.WithOrigins("http://localhost:4200"));
使用.ASPNet WebApi2时

更新

取自MSFT Docs:有很多方法可以实现CORS策略。一个例子是:在File WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // New code
        config.EnableCors();

        // existing code
    }
}

然后在你的控制器中:

[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

答案 1 :(得分:1)

即使您的前端设置为包含访问控制标头,您尝试访问的后端也未配置为接受您的来源。如果您控制后端,则尝试访问,即如果您可以更改代码,则需要将其更新为允许所有OPTIONS个请求,或者将其配置为允许localhost:4200来源。

如果您无权在后端进行更改,则可以通过proxy为您的应用程序提供服务。添加具有以下内容的proxy.conf.json就足够了:

{
    "/": {
        "target": "myurl",
        "secure": false
    }
}

其中myurl是后端api的网址。然后在启动应用程序时,包括代理配置位置:

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

答案 2 :(得分:0)

错误表示请求的资源不允许您传递。考虑将标题添加到您要访问的后端以允许您的localhost:4200,因为它不会让它通过

相关问题