问题描述
我在 ASP.NET Core 中创建了一个 webapi,我需要使用 React 来使用它,web api 可以正常工作,如果我使用 curl 或 postman 等,它可以正常工作.当我打算使用 React 时,当我尝试使用问题中的 js 对我的 API 发出任何请求时,问题就开始了.
I created a webapi in ASP.NET Core, and I need to consume it using React, the web api works normally, if I use curl or postman among others, it works normally. The problem starts when I'm going to use React, when I try to make any requests for my API with js from the problem.
更复杂的是,当我向其他 API 发出请求时,它正常工作,这让我相信问题出在我的 API 上,但正如我所说,它只与其他 API 一起工作,但反应却没有.我已经尝试了很多方法.
To complicate matters further, when I make the request for other APIs it works normally, this led me to believe that the problem was in my API, but as I said it works with others only with the react that it does not. I've tried it in many ways.
API 正在我本地网络上的 IIS 上运行
The API is running on an IIS on my local network
$ .ajax ({
method: "POST",
url: 'http://192.168.0.19:5200/api/token',
beforeSend: function (xhr) {
xhr.setRequestHeader ("Content-type", "application / json");
},
date: {
name: 'name',
password: 'password'
},
success: function (message) {
console.log (message);
},
error: function (error) {
/ * if (error.responseJSON.modelState)
showValidationMessages (error.responseJSON.modelState); * /
console.log (error);
}
});
使用提取
const headers = new Headers ();
headers.append ('Content-Type', 'application / json');
const options = {
method: 'POST',
headers,
body: JSON.stringify (login),
mode: 'cors' // I tried with cors and no-cors
}
const request = new Request ('http://192.168.0.19:5200/api/token', options);
const response = await fetch (request);
const status = await response.status;
console.log (response); * /
// POST adds a random id to the object sent
fetch ('http://192.168.0.19:5200/api/token', {
method: 'POST',
body: JSON.stringify ({
name: 'name',
password: 'password'
}),
headers: {
"Content-type": "application / json; charset = UTF-8"
},
credentials: 'same-origin'
})
.then (response => response.json ())
.then (json => console.log (json))
使用请求
var request = new XMLHttpRequest ();
request.open ('POST', 'http://192.168.0.19:5200/api/token', true);
request.setRequestHeader ('Content-Type', 'application / json; charset = UTF-8');
request.send (login);
错误
控制台
网络标签
当我在不将内容类型更改为 JSON 的情况下执行此操作时,它可以工作因为 API 返回说它不是有效类型.
When I do this without being change the content type to JSON it works because the API returns saying that it is not a valid type.
推荐答案
除了在你的 .NET 配置中允许 CORS.您还需要为所有 OPTION 请求返回 200 OK.
Apart from allowing CORS in you .NET configuration. You also need to return 200 OK for all OPTION requests.
不知道它是如何在 .NET 中完成的,但只是创建一个检测请求的 METHOD 的中间件,如果是 OPTIONS,则以 200 状态完成请求.
Not sure how it's done in .NET but just create a middleware that detects the METHOD of the request, and if it's OPTIONS, the finish the request right there with 200 status.
这篇关于我不能使用 json 使用 react 向我的 web api 发出 Post 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!