ajax - Koa-Bodyparser发送POST请求时出错 "invalid JSON, only supports object and array"

标签 ajax node.js post koa koa2

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

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)

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

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

我发送通常的 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 时,不会出现该错误。安装完毕后,我将其打印到 node.js 控制台(请注意 api.post(...) 中的 console.log 调用):

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

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

您能否解释一下为什么会出现此类错误并帮助我解决该问题?

最佳答案

通过字符串化 Ajax 请求中的 data 字段解决了这个问题。

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

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

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

关于ajax - Koa-Bodyparser发送POST请求时出错 "invalid JSON, only supports object and array",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821698/

相关文章:

javascript - jquery 函数被调用两次

php - AJAX-从php获取数据

javascript - 如何在用作nodejs服务器响应的html文件中包含外部脚本

node.js - MongoError : driver is incompatible with this server version

javascript - IE 8 中 AJAX 不一致?

rest - 使用 REST API 创建 Sonatype Nexus 存储库导致 HTTP/1.1 400 错误请求

javascript - 多个 JSON 对象

javascript - Nodejs cron 作业/每日作业 凌晨 2 点

ios - Alamofire POST 路由返回数据

javascript - 为什么 .length 在此代码中总是返回 0?