0

When i try to create a new "Flight" in this case with postman chrome plugin, I get the following error:

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

Mongoose Model:

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

Controller:

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

Routes:

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

and 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 works without problems but as soon as i post a request with postman that looks like:

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: "" }

i get the error 400 mentioned above. Can someone give me a hint? I'm lost.

1
  • Something's clearly up with your bodyparser. Can you step into that code somehow, or at least look at body-parser\lib\types\json.js:84:17 to put some logs around and see what's getting passed in that is causing it to throw? Commented May 28, 2015 at 5:22

1 Answer 1

2

you have to update your code in controller

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

in postman if you make post request means

x-www-form-urlencoded means don't pass Content-Type: application/json in header value

if you want pass raw formate means(third tab in post man)

header Content-Type : "application/json"

in raw content 


{
"field":"value"

}

example

{

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

}

in your request

{ 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: "" }

it should be

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

date should be json data formate

Sign up to request clarification or add additional context in comments.

1 Comment

Unbelievable. But i didn't see the missing quotes in my Post-Request. And due to the lack of a proper error message in the npm console i was pretty confused. Nicely seen! Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.