1 回答

TA貢獻1817條經驗 獲得超14個贊
問題就在這里:
request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(JSON.stringify(json));
在第一行中,您將內容類型設置為application/x-www-form-urlencoded。在第二個中,您的正文是一個 JSON 字符串。
您發送到該函數的數據是經過 urlencoded 的:
title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href
但在你的服務器上,你將正文解析為 json:
app.use(bodyParser.json());
您不能混合編碼。您需要決定是使用 JSON 還是 urlencoded:
JSON
在你的前端:
request_projets_post.setRequestHeader("Content-type", "application/json");
request_projets_post.send(JSON.stringify(json));
您提供給函數的數據是一個對象:
func_that_post_the_card_created(CHEMIN_AU_SERVEUR, {
title: title,
description: description,
imageUrl: imageUrl,
href: href,
github_href: github_href
});
后臺無需修改
URL編碼
不要使用 JSON.stringify:
const func_that_post_the_card_created = (path, data) => {
const request_projets_post = new XMLHttpRequest();
request_projets_post.open("POST", path, true);
request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request_projets_post.send(data);
};
func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href")
在您的服務器中刪除該行
app.use(bodyParser.json());
并添加:
app.use(bodyParser.urlencoded({ extended: true }));
添加回答
舉報