Monday 5 June 2017

Sending data with post request using superAgent

I'm new at Node.js and after some research on how to make a post request with superagent Im still unable to insert data into a form. When running the file, I always get the error message. Here's my code:

var superAgent = require('superagent');


const options = {
    host: '127.0.0.1',
    port: '8081',
    protocol: 'http:',
    path: '/',
    method: 'POST',


};

var req = http.request(options);

function agent(){

   superAgent.post('/process_post') //-> this is the action of the form
   .set('Content-Type', 'application/json')
   .send('{"fname":"Sir","surname":"Test","password":"123"}')
   .set('Accept', 'application/json')
   .end(function(err, res){
     if (err || !res.ok) {
       console.log('Error');
     } else {
       console.log('BODY ' + JSON.stringify(res.body));
     }
   });  
}
agent();

On the server side I have the following function that receives the inputs:

app.post('/process_post', urlencodedParser,function (req,res){

    var name= req.body.fname,
        surname=req.body.surname,
        password=req.body.password;


            db.collection('test').insertOne(
                { 'name': name, 'surname': surname,'password':password},
                function (err, r) {
                    assert.equal(null, err);
                    res.send("Document inserted with _id: " + r.insertedId);
                }
            );
         })



via Mellville

No comments:

Post a Comment