2016-11-26 1486 views
0

我試圖用一些參數向我的koa應用發送一個Ajax POST請求,但是我一直從koa-bodyparser接收到這個奇怪的錯誤每次我執行請求:發送POST請求時發送Koa-Bodyparser錯誤「無效的JSON,僅支持對象和數組」

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,錯誤不會出現。 insted的,我得到這個打印到控制檯的Node.js(請注意api.post(...)console.log電話):

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

似乎我不明白什麼是怎麼回事,爲什麼這樣的錯誤出現。

你能解釋爲什麼會出現這樣的錯誤並幫助我解決這個問題嗎?

回答

0

通過對Ajax請求中的data字段進行字符串化來解決此問題。

基本上,我改變了我的Ajax請求到這一點:

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

之後,我開始接受我的ctx.request body對象的內部服務器上的數據。