Fetch():请求正文格式错误

Fetch(): Request body malformed

我想向接受不同类型正文请求的 API 发出提取请求:twitter 句柄、facebook link、phone 号码等。正文是:

body: {
    "typeOfHandle": "input"
}

由于句柄有不同类型,我测试输入类型并相应地分配给主体,如下所示:

// handle is the input
let atSign = /^[@]/,    
    handleIsTwitter = atSign.test(handle.value),
    handleType;

handleIsTwitter ? handleType = `"` + "twitter" + `"` : console.log("not twitter");
let abc = `"` + handle.value + `"`;
let bodyOfFetch = `{${handleType}: ${abc}}`;
console.log("body: " + bodyOfFetch);
fetch("xxx", {
    method: "POST",
    headers: {
        Authorization: "xxx"
        },
    body: JSON.stringify(bodyOfFetch)
    })
    .then(function(res) {
        return res.json();
    })
    .then(function(json) {
        console.log(json);
    });

但是,这个方法returns出现了body malformed错误。当我静态地执行请求时(即用静态文本替换变量,例如 "twitter": "@alex"),它起作用了。我对语法进行了两次三重四次检查,我认为这不是问题所在。这会是 API 方面的问题吗?

在您的示例中,bodyOfFetch 是一个字符串 ({"twitter": "@alex"})。要么直接发,这个是:

fetch("xxx", {
method: "POST",
headers: {
    Authorization: "xxx"
    },
body: bodyOfFetch
})

或者您可以发送一个字符串化对象:

fetch("xxx", {
method: "POST",
headers: {
    Authorization: "xxx"
    },
body: JSON.stringify({[handleType]: abc})
})

但发送 JSON.stringify(bodyOfFetch) 将字符串化 json 字符串,这将添加周围的 " 并转义现有引号:"{\"twitter\": \"@alex\"}"

希望这对您有所帮助。