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

时间:2016-11-26 18:32:28

标签: ajax node.js post koa koa2

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?

2 个答案:

答案 0 :(得分:1)

通过对Ajax请求中的data字段进行字符串处理来解决它。

基本上,我将Ajax请求更改为:

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

然后我开始在ctx.request body对象内的服务器上接收数据。

答案 1 :(得分:1)

不确定是否会帮助我试图将数据中的字符串发送到Google Cloud Task的任何人,所以更改为发送到对象。

await client.createTask(
            { internalId: payload.internalId },
            payload.delayInSeconds,
            {
                headers: {
                    Authorization: `Bearer ${process.env.AUTH_TOKEN}1`,
                    "Content-Type": "application/json",
                },
            },
        );

类似这样的事情。 这里要学习的是不要在正文中发送字符串,而不是发送有效的对象。 本来是评论,但不会引起太多关注。