I'm attempting to post a JSON object to my server, but when I console log req.body it shows an empty object. Here's my code:
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);
}
I'm using express to transfer the server information, and I am using bodyParser.json(). From there, I just call the controller with the following:
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);
The createRecipe function just console logs the information, but as stated before, req.body is an empty object. All tips are appreciated.
I am using bodyParser.json()". So, I think we need the full code to see what is actually happening.