Tuesday 6 June 2017

Node.js: Can't insert form data in MongoDB with POST request

I'm trying to insert data into MongoDB with a script. Inserting it through the browser works fine, but not like this. I've followed posts like this but with no sucess. My console does log the data, but then it says

body: cannot post

Can anyone tell me what is wrong with this code? The request file:

const options = {
    host: '127.0.0.1',
    port: '8081',
    protocol: 'http:',
    path: '/',
    method: 'POST',
     headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var http = require('http');
var req = http.request(options);
var querystring = require('querystring');
var opn = require('opn');
var data = querystring.stringify({
      scoutName: 'john',
      scoutSurname: 'doe',
      scoutPassword:'123'

    });
 //opn('http://127.0.0.1:8081/');

    var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
console.log(data);
req.end();

And the server file:

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

   var name= req.body.scoutName,
        surname=req.body.scoutSurname,
        password=req.body.scoutPassword;

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


})



via Mellville

No comments:

Post a Comment