首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对本地主机上API的Angular 6应用调用被CORS阻止

对本地主机上API的Angular 6应用调用被CORS阻止
EN

Stack Overflow用户
提问于 2019-07-08 02:47:05
回答 2查看 3K关注 0票数 1

Mozilla dev tab network tabDetails of GET method called to 5001

我强行解决了一个问题,几个小时以来我都解决不了,这是很常见的,但是网上找到的提示都没有帮助到我。

Answer body

所有东西都在我本地的PC上。首先,我使用VS代码和命令行在Core2.1上开发了一些简单的ASP.NET核心WebAPI。这个WebAPI目前有一个简单的APIController,它托管在地址上:https://localhost:5001/api/customers/1 (当我将它粘贴到浏览器或邮递员上时,结果是我有一些简单的Json从数据库中返回了一个客户的数据)。当然,在Startup.cs类中,我添加了:

代码语言:javascript
复制
app.UseCors(options => 
            options.WithOrigins("http://localhost:4200/")
            .AllowAnyMethod()
            .AllowAnyHeader());

我也有一个过滤器:

代码语言:javascript
复制
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

它被添加到控制器内部和控制器API声明之上的每个方法中。

完整的控制器代码:

代码语言:javascript
复制
namespace BackEnd.Controllers
{
    [AllowCrossSiteJson]
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly ICustomersRepository _customersRepository;

        public CustomersController(ICustomersRepository customersRepository)
        {
            _customersRepository = customersRepository;
        }



        // GET api/customers
        [HttpGet]
        public async Task<string> Get()
        {

            var customer = await _customersRepository.GetRandomCustomer();

            return customer.FirstName.ToString();

           // return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [AllowCrossSiteJson]
        [HttpGet("{id}")]
        public async Task<Customer> Get(int id)
        {
            var customer = await _customersRepository.GetCustomerById(id);
            return customer;
        }

        // POST api/values
        [HttpPost]
        public async Task Post([FromBody] Customer customer)
        {
             await  _customersRepository.SaveCustomer(customer);

        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

我正在使用google Chrome浏览器。

其次-我有单独的项目开发与Node.Js在Angular 6.1.1。我想做一个快速测试,并从Angular应用程序调用Web API。所以在AppComponent中我添加了适当的httpClient注入,在OnInit方法中我添加了http.get请求,如下所示:

代码语言:javascript
复制
this.httpClient.get(`https://localhost:5001/api/customers/${id}`);

我的Angular应用程序最初是我PC上的adress http://localhost:4200上的Node.js服务器。(同时,WebAPI和Angular应用程序都在我的电脑上运行--在同一个Google Chrome中打开了两个选项卡)

当我启动http://localhost:4200并打开控制台中的Google Chrome Developer选项卡时,出现了一个错误:

CORS策略已阻止从源'http://localhost:4200‘访问'https://localhost:5001/api/customers/1’处的XMLHttpRequest :请求的资源上不存在' Access -Control-Allow- origin‘标头。

我在网上发现这个问题来自浏览器(Postman通常可以使用来自WebAPI的数据)我试图添加到我的带有内容的angular文件proxy.conf.json中:

代码语言:javascript
复制
{ 
    "/api/*": {
        "target": "https://localhost:5001",
        "secure": false,
        "changeOrigin": true
    }
}

但这对我一点帮助都没有。我不知道该去哪里看。

角度代码:

代码语言:javascript
复制
export class AppComponent {
  title = 'FrontEnd';

  constructor(private apiService: ApiService) { }

  ngOnInit(){
      console.log('hello');
      this.apiService.getCustomerById(1).subscribe((res) => {
         console.log(res);
      });
  }

  public getCustomerById(id :number) {
      return this.httpClient.get(`https://localhost:5001/api/customers/${id}`);
  }
}
EN

回答 2

Stack Overflow用户

发布于 2019-07-08 03:04:55

问题出在你的服务器上,而不是angular。您需要将web api设置为允许跨域资源共享。您可以通过向web api响应添加其他标头来执行此操作。

要了解如何做到这一点,请阅读以下答案

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

票数 2
EN

Stack Overflow用户

发布于 2019-07-08 03:05:15

Web浏览器防止网页向与提供该网页的域不同的域发出请求。这称为同源策略。对于每个这样的请求,浏览器都会调用一个OPTION来查找Access-Control-Allow-Origin标头。请求域应该包含在该标头中。您需要通过在ASP.NET核心项目中进行少量更改来启用此功能。

这篇文章可能会很有用:https://stackoverflow.com/a/31942128/4395295

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56925111

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档