简体   繁体   中英

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);


})

Use Mongoose for working with MongoDB in Node.js

var mongoose = require( 'mongoose' );
var Employee = mongoose.model( 'Employee' );

exports.addEmployee=function(req,res){                                  

                  var newEmployee=new Employee();

                  newEmployee.email=req.body.email;
                  newEmployee.name=req.body.name;
                  newEmployee.dob=req.body.dob;
                  newEmployee.sex=req.body.sex;
                  newEmployee.department=req.body.department;
                  newEmployee.age=req.body.age;

                  newEmployee.save(function(err,savedEmployee){
                       if(err){
                          var message="Error occured while storing new employee !!!";
                          console.log(message+"\n"+err);
                          res.status(500).send("Error Occured while saving Employee");
                        }else{
                         res.status(201).send(savedEmployee);
                          }
                 });

              }

And here is the mongoose schema

var employeeSchema = new mongoose.Schema({
  email: {type: String},
  name: {type: String},
  dob: {type: Date},
  sex:{type:String},
  department:{type:String},
  age:{type:Number}
});

mongoose.model( 'Employee', employeeSchema );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM