我试图通过使用Fetch API调用我自己的API来保存我的数据。但结果是继续回来415 Unsupported Media Type
。
客户端使用React JS和.NET Core MVC。服务器端使用Windows Server 2012上托管的.NET Core Web API。
我已经尝试了网络中提供的所有解决方案但是我仍然得到415错误。在IIS方面,我添加了Content-Type
和Accept
接受application/json
和text/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内部服务器错误。
我尝试使用.NET使用RestSharp,它能够正常发布,但不能在ReactJS中发布。所以我假设服务器端配置应该是正确的,但不是在客户端。
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对象,因为它会将它转换为一个字符串,您可以发送JSON对象本身而不将其转换为字符串。顺便说一下,如果我们在react应用程序中代理请求,我认为您不需要为每个请求启用CORS。您可以通过在package.json文件中添加此行来启用代理。
,
"proxy": "http://localhost:5000"
假设您的后端在localhost和端口5000上运行。