首页 文章

访问WebApi时不允许使用Angular 5 HTTP get方法

提问于
浏览
0

我有这项服务:

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 回答

  • 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"));
    

    UPDATE 使用.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

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

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

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

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

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

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

相关问题