使用Vanilla JS提交AJAX请求

时间:2017-11-13 14:06:56

标签: javascript node.js ajax mongodb express

这是我当前的代码,我想在服务器端将一个对象(配方)推送到一个数组中,但我还没有那么远。现在我只是尝试在服务器上安装console.log(配方)并获取未定义。

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(客户端):

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

JavaScript(服务器):

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

1 个答案:

答案 0 :(得分:0)

前端和后端都需要进行一些更改 前端更改

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}));
}

对于后端在express中使用json,你将不得不使用body解析器

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);
})