1

I have been having trouble accessing the data that is passed to express.js from angular http service.

I am using the http service :

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

This is what I am doing in angular:

$http.post('/api/topic', {data : topic}).then(successCallback, errorCallback);

This is what I am doing on in express:

app.post('/api/topic', function(req,res){console.log(req.data);});

We are assuming the topic is an object recieved from angular's frontend.

{
    username : 'dan',
    topic : 'I want to learn more',
    description : 'Where can I learn more about web development',
    category : 'web development'
}

So my question is : How does the backend end using express access the angular http data field?

2
  • if you're sending it via post, then you need to read the request body Commented Dec 23, 2015 at 21:32
  • if you are using express 4, you need to install body-parser Commented Dec 23, 2015 at 21:33

1 Answer 1

3

for POST requests you need body parser (get requests still access data)

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/api/topic', function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});
Sign up to request clarification or add additional context in comments.

6 Comments

This assumes ExpressJS 4
Yes I have body parser but the req.body return an empty object.
oh nevermind I was not parsing json. I missed out the app.use(bodyParser.json());
Post more of your code for better help. Try printing both the request data and request body see what you get. Are you absolutely sure that the data is sent? did you check the dev console (Chrome and Firefox both have it readily available) to see what's sent.
I was only parsing form and I only used app.use(bodyParser.urlencoded({ extended: true })); thanks for the insight.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.