Ryan Ryan - 27 days ago 10
Javascript Question

Attempting to send object from client to server (AngularJS $http.post)

I'm attempting to store an object that my user clicks on in my server so that when the page changes, all the information from that object can be displayed fully in a profile page.

I'm unfamiliar with Angular $http but I've tried to write a call that will POST to the server, unfortunately when I scan through the

req
object in VScode I can't find where the object I sent is contained, so I can send it on to my function.

Controller function:

$scope.storeProfile = function(child){
$http.post('/storeTempProfile', child)
.then(function(response) {
window.location.href = 'DemoPage.html';
});
}


server.js:

app.post('/storeTempProfile', function (req, res) {
profileStorage.storeProfile(req);
});


does my app.post look right? And what property of
req
do I need to use the dot operator on to access my object? I can't seem to find the object data anywhere in
req
and that makes me thing there's something wrong with how I wrote app.post

Answer

It looks like you are using express. So in that case, you want to access the object on req.body, but this will require you use body-parser. The example on their homepage:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400)
    // create user in req.body
})

You will notice in this example that they pass the json parser into the route itself. This is only necessary if you want to have different parsers for different routes. Usually you just want to set it to all routes, which you can do by using app.use(bodyParser.json()).