Search code examples
ajaxnode.jspostkoakoa2

Koa-Bodyparser error when sending POST request "invalid JSON, only supports object and array"


I'm trying to send an Ajax POST request with some parameters to my koa app, but I keep getting this weird error from koa-bodyparser each time I perform the request:

Error: invalid JSON, only supports object and array at parse (/home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:55:13) at /home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:41:16 at process._tickCallback (internal/process/next_tick.js:103:7)

and on the client side I get this error printed to the browser console:

jquery-1.12.3.js:10261 POST http://localhost:3000/api/v1/books 400 (Bad Request)

I send the usual jquery ajax request like this:

$.ajax({
  url: '/api/v1/books',
  data: {test: 'test-data'},
  dataType: 'json',
  contentType:  'application/json',
  type: 'POST'
});

and the code that processes the request is below:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const api = require('koa-router')({
    prefix: '/api/v1'
});
// I require 'koa-router' twice because
// 'api' and 'router' objects are originally located
// in different files, but here I've put them all
// together for conciseness.

router
    .get('home', '/', async (ctx, next) => { //...// })
    .get('test', '/test', async (ctx, next) => { //...// });

const app = new Koa();

api
    .get('/books', async (ctx, next) => {
        const books = await executePLSQL();
        const data = {
            data: prepareData(books)
        };
        ctx.body = JSON.stringify(data);
    })
    .post('/books', async (ctx, next) => {
        console.log('Test POST request:');
        console.log(ctx.request.body);
        console.log(ctx.params);

        ctx.status = 201;
    });

app
    .use(bodyParser())
    .use(router.routes())
    .use(api.routes())
    .use(api.allowedMethods())
    .use(router.allowedMethods());

app.listen(3000);

Sending GET requests works fine, but when I try to send a POST request, I get the error described above.

And here's another thing:

When I do not specify content-type in my Ajax request, the error does not appear. Insted, I get this printed to the node.js console (note the console.log calls in api.post(...)):

Test POST request:
{ undefined: '' }
{}

I don't seem to understand what is going on here and why such error is appearing.

Could you please explain why such error is appearing and help me to resolve that issue?


Solution

  • Solved it by stringifying the data field in the Ajax request.

    Basically, I changed my Ajax request to this:

    $.ajax({
      url: '/api/v1/books',
      data: JSON.stringify({test: 'test-data'}),
      dataType: 'json',
      contentType:  'application/json',
      type: 'POST'
    });
    

    and after that I started to receive the data on my server inside the ctx.request body object.