由于CORS无法获取标头而导致发布问题

Pue*_*rto 6 iis fetch cors reactjs

这个CORS让我再次屈服。我的意思是令人沮丧。请理解,在您否决我之前,我一直在搜索有关该主题的所有500万个帖子。我意识到在这个问题上有很多东西。这是我的React UI代码中的Fetch Post。它在带有已编译JS的IIS服务器上运行,对于SPA仅运行Index.html。我试图在同一服务器的不同端口上调用API。这是在Chrome和其他现代浏览器中杀死我的预兆(在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'
            })
        })
    );
Run Code Online (Sandbox Code Playgroud)

我们都已经看到了标准的预赛错误。

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

这是预检的小提琴:

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
Run Code Online (Sandbox Code Playgroud)

现在,我了解到,设置no-cors基本上会设置一个默认标头,这也不是我想要的,我需要我的application / json,因为谁不想要JSON,对吗?:)

我很乐意为解决此问题提供任何建议。基本上,因为这只是在IIS服务器上编译的Javascript和index.html,所以我需要了解处理似乎正在发生的这些预检选项检查的最佳解决方案。

******更新

我尝试添加webconfig来强制IIS服务器处理预检。似乎需要同时使用UI和API?

这是我的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>
Run Code Online (Sandbox Code Playgroud)

还有我的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>
Run Code Online (Sandbox Code Playgroud)

我现在得到的是:

提取API无法加载http:// myApiServer:81 / values / dui /。飞行前响应具有无效的HTTP状态代码415。

这是小提琴。

要求

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
Run Code Online (Sandbox Code Playgroud)

和回应

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
Run Code Online (Sandbox Code Playgroud)

Pue*_*rto 4

从那以后,我的 dotnet core webAPi 改用了这个解决方案。我发现它更干净,因为我不需要 webconfig 加上 cors 配置,需要将其设置得恰到好处才能使两者协同工作。这消除了 webConfig 中的 cors 内容,因此您只能将其设置在一处,即 API 应用程序代码本身中。

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

只是对链接中的内容进行简要总结。

添加到project.json

//Cross Origin Resource Sharing
"Microsoft.AspNetCore.Cors": "1.0.0"
Run Code Online (Sandbox Code Playgroud)

在启动时将其添加到您的配置服务中。

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;
})
);
Run Code Online (Sandbox Code Playgroud)

也可以在启动时配置

//Enable CORS policy "AllowCors"
    app.UseCors("AllowCors");
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中确保您有这些引用:

 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Cors;
 using CrossOrigin.WebService.Models.DbEntities;
 using Microsoft.EntityFrameworkCore;
Run Code Online (Sandbox Code Playgroud)

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

[EnableCors("AllowCors"), Route("api/[controller]")]
 public class ContactController : Controller
Run Code Online (Sandbox Code Playgroud)