获取 CORS 未获取标题的 Post 问题 [英] Fetch Post issues with CORS not getting header

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

问题描述

这个 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/values/dui/.对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头.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 基本上会设置一个默认标头,这也不是我想要的,我需要我的 application/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? :)

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

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=".logsstdout" 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.

这里是这个的小提琴.

请求

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 core 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;
})
);

也可以在启动时配置

//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 未获取标题的 Post 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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