我在 ASP.NET Core 中创建了一个 webapi,我需要使用 React 来使用它,web api 正常工作,如果我使用 curl 或 postman 等,它可以正常工作。当我打算使用 React 时,问题就开始了,当我尝试使用来自问题的 js 对我的 API 发出任何请求时。
更复杂的是,当我向其他 API 发出请求时,它可以正常工作,这让我相信问题出在我的 API 中,但正如我所说,它只能与其他人一起工作,但react却并非如此。我已经尝试了很多方法。
API 正在本地网络上的 IIS 上运行
尝试的方法
使用 Ajax
$ .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 返回说它不是有效类型。