Я пытаюсь отправить объект JSON на свой сервер, но когда я консольный журнал req.body
, он показывает пустой объект. Вот мой код:JavaScript/Nodejs: ajax POST-запрос, не передающий объект на бэкэнд
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);
}
Узел
createRecipe = function(req, res){
console.log(req.body);
}
Я использую экспресс для передачи информации о сервере, и я использую bodyParser.json()
. Оттуда, я просто называю контроллер со следующим:
выразить
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
является пустым объектом. Все советы приветствуются.
Вы используете express.js? если это правильно настроить BodyParer? – Iceman
Cud вы отправляете больше своего кода node.js? – Iceman
, чтобы следить за комментарием @ Iceman, убедитесь, что вы настроили body-parser для использования JSON, а не urlencoded. – zim