Node.js:不能使用POST请求在MongoDB中插入表单数据

时间:2017-06-06 10:01:42

标签: javascript node.js mongodb post

我试图用脚本将数据插入MongoDB。通过浏览器插入它可以正常工作,但不是这样。我跟着像this这样的帖子,但没有成功。我的控制台会记录数据,但随后会显示

body: cannot post

有谁能告诉我这段代码有什么问题?请求文件:

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

服务器文件:

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


})

1 个答案:

答案 0 :(得分:0)

使用Mongoose在Node.js中使用MongoDB

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

              }

这是mongoose架构

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