使用CORS获取帖子问题而不是获取标题 [英] Fetch Post issues with CORS not getting header

查看:807
本文介绍了使用CORS获取帖子问题而不是获取标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个CORS再次让我跪倒在地。我的意思是它可以令人沮丧。在你投票给我之前,请理解我一直关注这个主题的所有500万个帖子。我意识到这个主题有很多。这是我的React UI代码中的Fetch Post。这是在带有已编译JS的IIS服务器上运行的,而且只是用于SPA的Index.html。我试图在同一服务器上调用API不同的端口。这是在Chrome和其他现代浏览器中杀死我的预检(在IE中似乎很好)。

This CORS has brought me to my knees again. I mean it can be so discouraging. Please understand I have been looking at all 5 million posts on this topic before you down vote me. I realize there is a lot out there on this subject. Here is my Fetch Post in my React UI code. This is running on a IIS server with the compiled JS, and just Index.html for the SPA. Im trying to call a API on the same server different port. It's the preflight that is killing me in Chrome and other modern browsers (seems fine in IE).

这是获取:

    return (
        fetch(mypost, {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Accept": "application/json",
            },
            mode: 'cors',
            body: JSON.stringify({
                name: this.state.value,
            })
        }).then(response => {
            if (response.status >= 400) {
                this.setState({
                    value: 'no greeting - status > 400'
                });
                throw new Error('no greeting - throw');
            }
            return response.text()
        }).then(data => {
            var myData = JSON.parse(data);
            this.setState({
                greeting: myData.name,
                path: myData.link
            });
        }).catch(() => {
            this.setState({
                value: 'no greeting - cb catch'
            })
        })
    );

我们都看到了标准的预见错误。

standard prefight error we've all seen.

Fetch API无法加载 http:/ / myApiServer:81 /值/ DUI / 。对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin标头。因此,不允许访问 http:// localhost:82 。如果不透明的响应满足您的需求,请将请求的模式设置为no-cors以获取禁用CORS的资源。

Fetch API cannot load http://myApiServer:81/values/dui/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:82' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是小提琴预检:

OPTIONS http://myApiServer:81/values/dui/ HTTP/1.1
Host: myApiServer:81
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:82
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin, content-type
Accept: */*
Referer: http://localhost:82/validator
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

现在我已经了解到设置no-cors基本上会设置一个默认标头,这不是什么我也想要,我需要我的应用程序/ json,因为谁不想要JSON,对吧? :)

Now I have learned that setting no-cors will basically set a default header, which is not what I want either, I need my application/json, cause who doesn't want JSON, right? :)

我很想知道如何解决这个问题。基本上因为这只是编译Javascript和index.html坐在IIS服务器上,我需要知道处理这些似乎正在发生的预检选项检查的最佳解决方案。

I would love any advice on what I can do to resolve this issue. Basically since this is just compiled Javascript and index.html sitting on a IIS server, I need to know the best solution for dealing with these preflight options checks that seem to be happening.

******更新

我尝试添加webconfig以强制IIS服务器处理预检。它似乎需要在两端,我的UI和API?

I've tried adding webconfig to force the IIS server to handle the preflight. It seems like it needs to be on both ends, my UI and API??

这是我的UI Web.Config

Here is my UI Web.Config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

我的WebApi web.config

And my WebApi web.config

  <?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <handlers>
    <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
  </handlers>
  <httpProtocol>
    <customHeaders>
     <add name="Access-Control-Allow-Origin" value="*" />
     <add name="Access-Control-Allow-Headers" value="Content-Type" />
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
    </customHeaders>
  </httpProtocol>
  <aspNetCore processPath="dotnet" arguments=".\dui.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
 </system.webServer>
 </configuration>

我现在所有的现在是:

fetch API无法加载 http:// myApiServer:81 / values / dui / 。预检的响应具有无效的HTTP状态代码415.

fetch API cannot load http://myApiServer:81/values/dui/. Response for preflight has invalid HTTP status code 415.

这是这个的小提琴。

req

OPTIONS http://myApiServer:81/values/dui/ HTTP/1.1
Host: myApiServer:81
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:82
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:82/validator
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

和回复

HTTP/1.1 415 Unsupported Media Type
Content-Length: 0
Server: Kestrel
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Date: Thu, 02 Mar 2017 18:35:31 GMT


推荐答案

我已经切换了为我的dotnet核心webAPi寻找此解决方案。我发现它更干净,因为我不需要webconfig加上cors配置,需要设置正确的2才能协同工作。这消除了你的webConfig中的cors东西,所以你只能在一个地方设置它,在你的API应用程序代码本身。

I have since switched to this solution for my dotnet core webAPi. I find it's cleaner since I don't need a webconfig plus the cors config which needs to be set just right for the 2 to work together. This gets rid of the cors stuff in your webConfig so your only setting it in one place, in you API application code itself.

https://www.codeproject.com/Articles/1150023/Enable-Cross-origin-Resource-Sharing-CORS-in-ASP-N

只是简单概述一下链接中的内容。

Just to give a brief summary of what's in the link.

添加到project.json

Add to project.json

//Cross Origin Resource Sharing
"Microsoft.AspNetCore.Cors": "1.0.0"

在启动时添加此项到您的ConfigureServices。

In startup add this to your ConfigureServices.

services.AddCors(
options => options.AddPolicy("AllowCors",
builder =>
{
    builder
    //.WithOrigins("http://localhost:4456") //AllowSpecificOrigins;
    //.WithOrigins("http://localhost:4456", 
    "http://localhost:4457") //AllowMultipleOrigins;
    .AllowAnyOrigin() //AllowAllOrigins;

    //.WithMethods("GET") //AllowSpecificMethods;
    //.WithMethods("GET", "PUT") //AllowSpecificMethods;
    //.WithMethods("GET", "PUT", "POST") //AllowSpecificMethods;
    .WithMethods("GET", "PUT", 
    "POST", "DELETE") //AllowSpecificMethods;
    //.AllowAnyMethod() //AllowAllMethods;

    //.WithHeaders("Accept", "Content-type", "Origin", "X-Custom-Header");  
    //AllowSpecificHeaders;
    .AllowAnyHeader(); //AllowAllHeaders;
})
);

此外还可以在启动时配置

Also at it to Configure in Startup

//Enable CORS policy "AllowCors"
    app.UseCors("AllowCors");

然后在你的控制器中确保你有这些参考:

Then in your controller ensure you have these references:

 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Cors;
 using CrossOrigin.WebService.Models.DbEntities;
 using Microsoft.EntityFrameworkCore;

最后将属性添加到控制器类中。

And Finally add the attribute to your controller class.

[EnableCors("AllowCors"), Route("api/[controller]")]
 public class ContactController : Controller

这篇关于使用CORS获取帖子问题而不是获取标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆