【问题标题】:Koa-Bodyparser error when sending POST request "invalid JSON, only supports object and array"发送 POST 请求时 Koa-Bodyparser 错误“无效 JSON,仅支持对象和数组”
【发布时间】:2017-04-10 20:11:08
【问题描述】:

我正在尝试向我的 koa 应用程序发送一个带有一些参数的 Ajax POST 请求,但每次执行请求时我都会从 koa-bodyparser 收到这个奇怪的错误:

错误:无效的 JSON,只支持对象和数组 在解析(/home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:55:13) 在/home/denis/WEB/nodejs/kinfs/node_modules/co-body/lib/json.js:41:16 在 process._tickCallback (internal/process/next_tick.js:103:7)

在客户端,我将此错误打印到浏览器控制台:

jquery-1.12.3.js:10261 发布http://localhost:3000/api/v1/books 400 (错误请求)

我像这样发送通常的 jquery ajax 请求:

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

处理请求的代码如下:

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

发送 GET 请求工作正常,但是当我尝试发送 POST 请求时,我收到上述错误。

还有一件事:

当我没有在我的 Ajax 请求中指定 content-type 时,不会出现错误。 Insted,我将此打印到 node.js 控制台(注意 api.post(...) 中的 console.log 调用):

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

我似乎不明白这里发生了什么以及为什么会出现这样的错误。

您能否解释一下为什么会出现这样的错误并帮助我解决这个问题?

【问题讨论】:

    标签: ajax node.js post koa koa2


    【解决方案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 对象内的服务器上接收数据。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        • 2022-07-11
        • 1970-01-01
        • 2015-05-04
        相关资源
        最近更新 更多