使用Node,Bodyparser和MongoDB发出请求时Object.parse处的语法错误

时间:2015-05-28 05:11:43

标签: mongodb express mongoose mean-stack

当我尝试使用postman chrome插件创建一个新的“Flight”时,我收到以下错误:

SyntaxError: Unexpected token d
at Object.parse (native)
at parse (D:\data\coding\nodeprojects\flightlog\fl-server\node_modules\body-parser\lib\types\json.js:84:17)
at D:\data\coding\nodeprojects\flightlog\fl-server\node_modules\body-parser\lib\read.js:102:18
at done (D:\data\coding\nodeprojects\flightlog\fl-server\node_modules\body-parser\node_modules\raw-body\index.js:248:14)
at IncomingMessage.onEnd (D:\data\coding\nodeprojects\flightlog\fl-server\node_modules\body-parser\node_modules\raw-body\index.js:294:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11

猫鼬模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var FlightSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    date: Date,
    registration: String,
    pic: String,
    pnf: String,
    departure: String,
    arrival: String,
    takeOff: String,
    landing: String,
    landingCount: Number,
    remarks: String
});

FlightSchema.statics = {
    load: function (id, cb) {
        this.findOne({
            _id: id
        }).exec(cb);
    }
};

mongoose.model('Flight', FlightSchema);

控制器:

require('../models/flight');
var mongoose = require('mongoose');
var Flight = mongoose.model("Flight");

exports.post = function (req, res) {
    var flight = new Flight(req.body);
    flight.save();
    res.jsonp(flight);
};

exports.get = function (req, res) {
    Flight.find().exec(function (err, flights) {
        res.jsonp(flights)
    });
};

路线

var express = require('express');
var router = express.Router();

var flightsController = require('../controllers/flightsController');

/* POST /flights */
router.post('/', flightsController.post);

// GET /flights/
router.get('/', flightsController.get);

app.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var cors = require('cors');

var users = require('./routes/users');
var flights = require('./routes/flights');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/flightlog');
var db = mongoose.connection;

db.on('error', function callback() {
    console.log("MongoDB connection failed");
});

db.once('open', function callback() {
    console.log("Successfully connected");
});

//app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());

app.use('/users', users);
app.use('/flights', flights);

/// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

npm start 可以正常运行,但只要我发布请求邮递员,就会发现:

POST /flights HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache

{ date: "2015-01-01 14:00", registration: "ABC123", pic: "J. Cash", pnf: "J. Carter", departure: "KJFK", arrival: "KLAX", takeOff: "2015-01-01 14:00", landing: "2015-01-01 14:30", landingCount: 1, remarks: "" }

我得到上面提到的错误400。有人能给我一个暗示吗?我输了。

1 个答案:

答案 0 :(得分:2)

您必须更新控制器中的代码

require('../models/flight');
var mongoose = require('mongoose');
var Flight = mongoose.model("Flight");

// in controller post action code is updated ******************* 
exports.post = function (req, res,next) {
    var flight = new Flight(req.body);
    flight.save(function(err, result){

if(!err)
{
res.json(201,result);
}else
{

next(err);
}


});

};

exports.get = function (req, res) {
    Flight.find().exec(function (err, flights) {
        res.jsonp(flights)
    });
};
如果您提出邮寄请求,邮递员

x-www-form-urlencoded表示不在标题值中传递Content-Type:application / json

如果你想通过原始甲酸盐手段(邮政人员中的第三个标签)

header Content-Type : "application/json"

in raw content 


{
"field":"value"

}

example

{

"firstName":"David",
"lastName":"S"

}

在您的请求中

{ date: "2015-01-01 14:00", registration: "ABC123", pic: "J. Cash", pnf: "J. Carter", departure: "KJFK", arrival: "KLAX", takeOff: "2015-01-01 14:00", landing: "2015-01-01 14:30", landingCount: 1, remarks: "" }

应该是

{ "date": "2015-01-01 14:00", "registration": "ABC123", "pic": "J. Cash", pnf: "J. Carter", "departure": "KJFK", "arrival": "KLAX",.............}

日期应为 json 数据格式