gpt4 book ai didi

JavaScript/Node : ajax POST request not passing object to backend

转载 作者:行者123 更新时间:2023-11-30 11:55:06 26 4
gpt4 key购买 nike

我试图将一个 JSON 对象发布到我的服务器,但是当我在控制台日志 req.body 中显示一个空对象。这是我的代码:

var submitRecipe = () => {

let recipe = {alias: null, description: null, instructions: null};
recipe.alias = document.getElementById('alias').value;
recipe.description = document.getElementById('description').value;
recipe.instruction = document.getElementById('instructions').value;

postRequest("/createrecipe", recipe, (xhr) => {
console.log("Hello!" + JSON.parse(xhr.responseText));
})
};
var postRequest = (url, data, callback = undefined) => {

xhr.onreadystatechange = () => {
//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
console.log("testing");
return callback(200 , xhr.responseText);
}else{
return callback(400, xhr.responseText);
}
}
xhr.open('POST', url)
xhr.send(data);
}

Node

createRecipe = function(req, res){

console.log(req.body);
}

我正在使用 express 来传输服务器信息,我正在使用 bodyParser.json()。从那里,我只需使用以下内容调用 Controller :

express

var express = require("express");
var bodyParser = require("body-parser");

var server = express();

var recipeController = require("./controllers/recipeController");

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true}));


server.post("/createrecipe", recipeController.createRecipe);

createRecipe 函数只是控制台记录信息,但如前所述,req.body 是一个空对象。感谢所有提示。

最佳答案

与 jQuery 或 Angular Ajax 包装函数等其他库包装器不同,XHR 期望您的数据以您希望发送的任何方式进行编码或打包。此外,body-parser中间件没有识别内容类型,也没有为所需的请求激活。

简单地 JSON.stringify 你的 json 数据

data = JSON.stringify(data);

并将 application/json MIME 类型添加为 xhrcontent-type header 。

xhr.setRequestHeader("content-type", "application/json");

此外,如果您想使用url-encoded,请在附加之前对您的数据进行编码,并添加相应的 header 内容类型。

我的完整测试代码(供引用):

服务器(testServer.js):

var express = require("express");
var bodyParser = require("body-parser");

var server = express();

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true}));

server.post("/createrecipe", function(req, res){
console.log(req.body);
var resp = {server: "hello world", dataReceived: req.body};
res.json(resp);
});

server.get("/", function(req, res){
res.sendFile(__dirname + "/testClient.html");
})

server.listen(3000, function(){
console.log("Server running");
})

客户端(testClient.html):

<input type="text" id="alias" value="a">
<input type="text" id="description" value="b">
<input type="text" id="instructions" value="c">
<button onclick="submitRecipe()"> TEST</button>
<script>
var submitRecipe = () => {

let recipe = {alias: null, description: null, instructions: null};
recipe.alias = document.getElementById('alias').value;
recipe.description = document.getElementById('description').value;
recipe.instructions = document.getElementById('instructions').value;

postRequest("/createrecipe", recipe, (status, xhr) => {
var data = (JSON.parse(xhr.responseText));
console.log(data.dataReceived);
})
};
var postRequest = (url, dataObj, callback = undefined) => {
//--------------Added line--------------------
var data = JSON.stringify(dataObj);
//--------------Added line--------------------
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
return callback(200 , xhr);
}else if(xhr.status == 400){
return callback(400, xhr);
}
}
xhr.open('POST', url)
//--------------Added line--------------------
xhr.setRequestHeader("content-type", "application/json");
//--------------Added line--------------------
xhr.send(data);


}
</script>

关于JavaScript/Node : ajax POST request not passing object to backend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38255890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com