Express routing post call unexpected token in json

I need some help with my routing in Express and making a post call, and retrieving the data within the postrequest.

I've tried retrieving the data by loging req.body but that returns {}, I tried adding the bodyParser to my App.js which gets me the following error when I make a post call:

POST http://localhost:3000/enquete/test/ 400 (Bad Request)

SyntaxError: Unexpected token # in JSON at position 0

This is my code:


const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient
  , co = require('co')
  , assert = require('assert')
  , bodyParser = require('body-parser');
var indexRouter = require('./routes/index.js');
var enqueteRouter = require('./routes/enquete.js');

// support parsing of application/json type post data

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/enquete', enqueteRouter);
app.use(express.static(__dirname + '/routes'));
app.use(express.static(__dirname + '/public'));

app.listen(3000, () => console.log('Example app listening on port 3000!'))


const express = require('express')
var router = express.Router()'/test/', function(req,res,next){
module.exports = router;

Ajax post call

function save(array){
        type: 'POST',
        data: { name: "Test", location: "TestUSA" },
        contentType: 'application/json',
                url: 'http://localhost:3000/enquete/test/',
                success: function(data) {
                error: function(error) {
                        console.log('error:', error)

enter image description here

1 answer

  • answered 2018-03-13 20:33 zer0kompression

    Can you use Postman to test the route? Make sure to select x-www-form-urlencoded as the body format since you're using bodyparser.urlencoded({ extended: true })