gpt4 book ai didi

json - react : Fetch API getting 415 Unsupported Media Type using POST

转载 作者:行者123 更新时间:2023-12-03 14:31:00 90 4
gpt4 key购买 nike

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

客户端使用 React JS 和 .NET Core MVC。服务器端使用 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 内部服务器错误。

我尝试使用 RestSharp 使用 .NET,它能够正常 POST,但不能在 ReactJS 中。所以我认为服务器端配置应该是正确的,但客户端配置不正确。

最佳答案

这肯定是由 mode: no-cors 和服务器的 cors 策略共同导致的。

通过使用模式:no-cors,您可以使用的唯一 header 是 simple headers ,又名“CORS 安全列表请求 header ”,仅包含 application/x-www-form-urlencodedmultipart/form-datatext/普通

此行为已记录 here :

no-cors — Prevents the method from being anything other than HEAD, GETor POST, and the headers from being anything other than simpleheaders. If any ServiceWorkers intercept these requests, they may notadd or override any headers except for those that are simple headers.In addition, JavaScript may not access any properties of the resultingResponse. This ensures that ServiceWorkers do not affect the semanticsof the Web and prevents security and privacy issues arising fromleaking data across domains.

所以我会:

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

关于json - react : Fetch API getting 415 Unsupported Media Type using POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55627884/

90 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com