简体   繁体   中英

Submitting AJAX request using Vanilla JS

Here is my current code, I want to push an object (recipe) into an array at the server side, but I haven't even gotten that far yet. Right now I'm just trying to console.log(recipe) on server and getting undefined.

HTML:

<button type='button' class='btn btn-warning add-recipe'><i class="fa fa-book" aria-hidden="true" onclick='addRecipe(<%= JSON.stringify(recipe.author.id) %>)'></i></button>

JavaScript (client):

function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.send({recipe: recipe});
}

JavaScript (server):

router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})

Some changes are required in both frontend and back-end Front-end changes

function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
   xml.send(JSON.stringify({recipe: recipe}));
}

For the backend to consume json in express you will have to use the body parser

var bodyParser = require('body-parser');
// I am assuming router the name of your express app 
router.use(bodyParser.json());

router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM