0

https://codeforgeek.com/2014/07/angular-post-request-php/

Hi I was following the above link to give post request from angular js to node js. I received the data posted in below format when i give

console.log(req.body);
{ '{"email":"[email protected]","pass":"password"}': '' }

and when i try to get the value as below, it says undefined.

var email = req.body.email;
 console.log(email);

I am unable to get the value of email and pass. Thank you

2
  • That's a string not an object, where is your Angular code? I mean it's an object but it's not what you want Commented Jul 9, 2015 at 10:28
  • I think you sent it wrong from browser Commented Jul 9, 2015 at 10:41

3 Answers 3

1

change the client side header code to headers: { 'Content-Type': 'application/json' }

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That seemed to be the problem. I fixed it now :)
0

Your Angular code is sending JSON data, but your Express app is parsing it as URL encoded data.

You probably have something like this in your Express app:

var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded());

That last line should be:

app.use(bodyParser.json());

2 Comments

var bodyParser = require('body-parser'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); //mongoose.connect(database.url); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.use('/login', require('./routes/login')); This my current code, in app.Js
@AddieVanhala in that case, it seems to me that your client side code isn't sending the correct HTTP headers (to indicate that the body data is JSON)
0

You did not well explain the problem , please next time try to post a bigger part of your code so we could understand what you wanted to do / to say .

To answer your question i will copy/paste a part of my code that enable you to receive a post request from your frontend application(angularJS) to your backend application (NodeJS), and another function that enable you to do the inverse send a post request from nodeJS to another application (that might consume it):

1) receive a request send from angularJS or whatever inside your nodeJS app

    //Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')

      // we need these variables for the post request:


      var Vorname ;
      var Name ;
      var e_mail ;
      var Strasse ;


  app.use(myParser.urlencoded({extended : true}));
  // the post request is send from http://localhost:8080/yourpath
  app.post("/yourpath", function(request, response ) {
      // test the post request
      if (!request.body) return res.sendStatus(400);

      // fill the variables with the user data
       Vorname =request.body.Vorname;
       Name =request.body.Name;
       e_mail =request.body.e_mail;
       Strasse =request.body.Strasse;      
      response.status(200).send(request.body.title);

});

2) Do the inverse send a POST request from a nodeJS application to another application

    function sendPostRequest()
    {
        // prepare the data that we are going to send to anymotion  
        var jsonData = querystring.stringify({
                "Land": "Land",
                "Vorname": "Vorname",
                "Name": "Name",
                "Strasse": Strasse,
            });
        var post_options = {
            host: 'achref.gassoumi.de',
            port: '443',
            method: 'POST',
            path: '/api/mAPI',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': jsonData.length
            }
        };
        // request object
            var post_req = https.request(post_options, function(res) {
            var result = '';
            res.on('data', function (chunk) {
                result += chunk;
                console.log(result);
            });
            res.on('end', function () {
            // show the result in the console : the thrown result in response of our post request
            console.log(result);
        });
        res.on('error', function (err) {
            // show possible error while receiving the result of our post request
            console.log(err);
        })
        });
        post_req.on('error', function (err) {
            // show error if the post request is not succeed
            console.log(err);
        });
        // post the data
        post_req.write(jsonData);
        post_req.end(); 
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
    }

So finally , I hope this answer will helps anyone who is looking on how to get a post request in node JS and how to send a Post request from nodeJS application.

For further details about how to receive a post request please read the npm documentation for body-parser library : npm official website documentation

I hope you enjoyed this and Viel spaß(have fun in german language).

Comments

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.