javascript - 如何修复 “Failed to load resource: the server responded with a status of 400 ()” API获取错误

标签 javascript api asp.net-core fetch progressive-web-apps

我正在构建一个PWA应用程序,我需要在其中调用使用asp.net核心构建的API。当我尝试通过JavaScript fetch函数调用POST时,出现以下错误:
加载资源失败:服务器响应状态为400()

我通过 postman 测试了此API,并且工作正常。
我尝试获取GET方法,并且工作正常。

订阅模式:

    public class Subscription
    {
        public string endpoint { set; get; }
        public DateTime ? expirationTime { set; get; }
        public Key keys { set; get; }
    }


按键型号:

    public class Key
    {
        public string p256dh { set; get; }
        public string auth { set; get; }
    }

后API Controller :
    [Route("api/[controller]")]
    [ApiController]
    public class PushNotificationController : ControllerBase
    {
       [HttpPost]
        public void Post([FromBody] Subscription sub )
        {
            Console.WriteLine(sub);
        }
    }

提取 call
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();


任何的想法?

更新:

我用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);
        });

最佳答案

使用对象:

fetch('https://localhost/', {
    method: 'POST',
    body: {
        foo: "bar"
    }
})

在这种情况下,正文可能是:[object Object]

但是将对象转换为JSON:

fetch('https://localhost/', {
    method: 'POST',
    body: JSON.stringify({
        foo: "bar"
    })
})

正文将为{"foo":"bar"}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options

关于javascript - 如何修复 “Failed to load resource: the server responded with a status of 400 ()” API获取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435467/

相关文章:

javascript - 使用 requireJS 加载 IE 依赖

php - 如何创建可编辑的下拉列表?使用 AJAX

php - 如何在 PayPal 沙盒账户中启用 DPRP?

api - 如何使用Rust通过访问 token 提交新的github问题

具有 (CSP) 内容安全策略的 Angular 5 和 ASP.Net Core

javascript - 部署时出现错误 firebase 函数 [Promises 必须得到适当处理]

php - 用于游戏的 Google Play 商店 API

c# - 具有多个参数的 webapi 方法的自定义模型绑定(bind)器

c# - 代码 : TokenNotFound Message: User not found in token cache. 可能服务器已重新启动

javascript - if (!options.algorithms) throw new Error ('algorithms should be set' );错误 : algorithms should be set