Error: invalid JSON, only supports object and array:报错详解

    技术2022-07-11  118

    问题重现:

    问题大意:发送POST请求时发送Koa-Bodyparser错误“无效的JSON,仅支持对象和数组”。此问题是使用koa开发的时候出现的,当我使用postman发送post请求时,后端使用koa-bodyparser接收数据时,出现了这个错误。

    后端代码:

    main.ts:

    import * as Koa from 'koa'; import { useControllers } from "koa-controllers"; import db from './models'; import * as koaBodyparser from 'koa-bodyparser' let app = new Koa(); app.use( async (ctx: Koa.Context, next) => { // 把db对象等其他一些数据挂在到当前的state下面 ctx.state.db = db; await next(); } ); app.use(koaBodyparser()); useControllers(app, __dirname + '/controllers/**/*.controller.js', { multipart: { dest: './uploads' } }); app.listen(3000);

    controller.ts:

    import {Controller,Get,Ctx,Post} from 'koa-controllers'; import {Context} from 'koa'; import db from '../models'; import { Model } from "sequelize"; @Controller export class AdminCategoryController { @Get('/admin/category') public async index(@Ctx ctx: Context) { let categoryModel = await <Model<any, any>>ctx.state.db['category'].findAll() ctx.body = categoryModel } @Post('/admin/category') public async add(@Ctx ctx: Context) { let pid = ctx.request.body.pid || 0 let name = ctx.request.body.name || 0 console.log(ctx.request.body); } }
    postman请求:

    错误展示:

    解决方法:

    主要原因还是post发送的数据格式问题,后端Koa-Bodyparser接受不了,如果传入后台的是字符串也不行,所以这边需要传入对象。所以需要先设置请求头 'Content-Type' : 'application/json;charset=utf-8'然后数据用json对象格式,如下: postman: 在js里面其实不用考虑这个问题,一般axios发送post请求,请求头就是这个格式,传递数据需要是对象格式:

    vue.js:

    axios({ method:'post', url:'/api/admin/category', data:{name: 'test-data',pid:0} })

    使用Ajax发送可以这样写: ajax.js:

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

    最终效果:

    Processed: 0.008, SQL: 9