Reputation: 3015
All my requests work perfectly except when I try to add an item to an array of json elements, it will return undefined every time.
Controller:
vm.addOptie = function () {
var newOptie = {"optie": 'stuur',"prijs": 150};
$http({
method: 'post',
url: 'http://localhost:3000/addGekozenOptie',
headers: {
'Content-Type': 'application/json'
},
data: newOptie
}).then(function (gekozenOpties) {
vm.gekozenOpties = gekozenOpties.data;
}).catch(function (err) {
alert('Er is een fout opgetreden: ' + err);
})
}
and my router/index.js
var router = require('express').Router();
var gekozenOpties = require('../public/data/opties.json');
router.post('/addGekozenOptie', function (req, res) {
var op = req.body;
gekozenOpties.push(op);
res.json(gekozenOpties);
});
module.exports = router;
Very frustrating seeing as everything else works fine (get/delete).
Upvotes: 1
Views: 3860
Reputation: 5606
Have you tried the following?
//install body-parser
npm install body-parser
//Sample code within your app
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body, or an empty object ({}) if there was no body to parse (or an error was returned).
Upvotes: 4