aln*_*ser 7 javascript fetch-api progressive-web-apps asp.net-core
我正在构建一个 PWA 应用程序,我需要调用使用 asp.net core 构建的 API。当我尝试通过 JavaScript fetch 函数调用 POST 时,出现以下错误:无法加载资源:服务器响应状态为 400 ()
我通过 Postman 测试了这个 API,它工作正常。我尝试了 GET 方法的 fetch,它工作正常。
订阅模式:
public class Subscription
{
public string endpoint { set; get; }
public DateTime ? expirationTime { set; get; }
public Key keys { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
按键型号:
public class Key
{
public string p256dh { set; get; }
public string auth { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
发布 API 控制器:
[Route("api/[controller]")]
[ApiController]
public class PushNotificationController : ControllerBase
{
[HttpPost]
public void Post([FromBody] Subscription sub )
{
Console.WriteLine(sub);
}
}
Run Code Online (Sandbox Code Playgroud)
取电话
async function send() {
await
fetch('https://localhost:44385/api/PushNotification', {
mode: 'no-cors',
method: 'POST',
body: { "endpoint": "123", "expirationTime": null, "keys": { "p256dh": "ttdd", "auth": "dssd" } },
headers: {
'content-type': 'application/json'
}
}).catch(function (erro) {
console.log("Error comunicateing to server");
});
}
send();
Run Code Online (Sandbox Code Playgroud)
任何想法?
更新:
我使用 JSON.stringify(data) 尝试了下面的代码,但仍然遇到相同的错误。
const data = {
endpoint: "123",
expirationTime: null,
keys: {
p256dh: "p256dh test",
auth: "auth test"
}
};
await
fetch('https://localhost:44385/api/PushNotification', {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'same-origin' ,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
}).catch(function (erro) {
console.log(erro);
});
Run Code Online (Sandbox Code Playgroud)
事实证明,问题出在cors模式上。删除它或将其设置为“cors”。
await fetch('https://localhost:44385/api/PushNotification', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin' ,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
}).catch(function (erro) {
console.log(erro);
});
Run Code Online (Sandbox Code Playgroud)