React:使用POST获取415不支持的媒体类型的API获取

时间:2019-04-11 08:22:53

标签: json asp.net-mvc reactjs iis fetch-api

我试图通过使用Fetch API调用自己的API来保存数据。但是结果是不断返回415 Unsupported Media Type

客户端正在使用带有.NET Core MVC的React JS。 服务器端正在使用Windows Server 2012上托管的.NET Core Web API。

我尝试了网络中提供的所有解决方案,但随后仍然出现415错误。在IIS方面,我添加了Content-TypeAccept以接受application/jsontext/plain

到目前为止,仅GET方法有效。 PUT,POST,DELETE全部无效。

下面是我在客户端的代码。

        fetch('https://mywebapi.net/api/event/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json, text/plain',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            mode: 'no-cors',
            body: JSON.stringify({
                eventId: 5,
                eventName: "Event 5",
                eventDescription: "Event 5 Description",
                eventLocation: "Kuala Lumpur, Malaysia",
                eventDateTime: "2019-03-28"
            }),
        }).then(response => response.text())
            .then(data => console.log(data))    
            .catch(error => console.log("Error detected: " + error))

如果我删除mode: 'no-cors',它将返回500 Internal Server Error。

我已经尝试过使用带有RestSharp的.NET,它能够正常发布,但不能在ReactJS中发布。因此,我认为服务器端配置应该正确,而不是客户端端。

2 个答案:

答案 0 :(得分:1)

这肯定是由 mode: no-cors 和您服务器的 cors 政策的组合引起的。

通过使用 mode: no-cors,您可以使用的唯一标头是 simple headers,也就是“CORS-safelisted request-headers”,它仅包含 application/x-www-form-urlencodedmultipart/form-data、或text/plain

此行为已记录在案 here

<块引用>

no-cors — 防止方法不是 HEAD, GET 或 POST,以及标题不是简单的 标题。如果任何 ServiceWorker 拦截了这些请求,他们可能不会 添加或覆盖除简单标头之外的任何标头。 此外,JavaScript 可能无法访问结果的任何属性 回复。这确保了 ServiceWorkers 不会影响语义 并防止由网络引起的安全和隐私问题 跨域泄露数据。

所以我会:

  1. 从您的请求中删除 mode: no-cors
  2. 检查您的服务器允许的来源以确保允许来自浏览器 IP 的请求(例如,如果您的 React 应用程序在 http://localhost:3000 上运行,请确保 http://localhost:3000 明确列为允许的来源.

答案 1 :(得分:0)

fetch('https://mywebapi.net/api/event/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json, text/plain',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            mode: 'no-cors',
            body: {
                "eventId": 5,
                "eventName": "Event 5",
                "eventDescription": "Event 5 Description",
                "eventLocation": "Kuala Lumpur, Malaysia",
                "eventDateTime": "2019-03-28"
            },
        }).then(response => response.text())
            .then(data => console.log(data))    
            .catch(error => console.log("Error detected: " + error))

在不字符串化 JSON 对象的情况下进行尝试,因为它会将其转换为 string ,因此您可以发送 JSON 对象本身,而不将其转换为字符串。 顺便说一句,如果我们在React应用程序中代理,则您无需为每个请求启用 CORS 。您可以通过在package.json文件中添加此行来启用代理。

 ,
  "proxy": "http://localhost:5000"

假设您的后端在localhost和端口5000上运行。