3
我正在嘗試使用fetch
API向我的服務器提供POST
數據,每次我最終都會得到一個空體。無法使用JavaScript獲取API POST數據
據我所知,從fetch
documentation可以知道,要發佈數據,您需要傳遞一個方法鍵設置爲「POST」的對象,並使用字符串或對象(或其他)傳遞主體鍵。
這裏的,這只是沒有工作,我期望一個簡單的例子:
var formData = new FormData();
formData.append("test", "woohoo");
formData.append("foo", "bar")
// prints out contents of formData to show that it has contents!
formData.forEach(function(key, value) {
console.log(`${key}: ${value}`);
});
fetch("/fetch", {
method: "POST",
body: formData
}).then(function(response) {
return response.json();
}).then(function(json) {
// Logs empty object
console.log(json);
}).catch(function(err) {
console.log(err);
});
我也有這個,它記錄請求主體和呼應它在響應中回一個Express服務器。
app.post("/fetch", function(req, res) {
// Logs empty object :(
console.log(req.body);
res.send(JSON.stringify(req.body));
});
我添加formData
爲fetch
請求的主體,但從來都沒有,似乎經歷。
Please find my test files in this gist here和幫助!
我相信你錯過了'扔新TennisBall()',這是你所需要的抓取。 :) – markthethomas