2016-12-24 26 views
0

我試圖做兩個不同的項目請求。我在快遞項目中使用快遞,但JSON解析錯誤請求使用請求模塊等項目兩個不同的項目請求json解析錯誤

例子中的物體

var data= { 
    User: { 
     ID: 123 
    }, 
    Text: 'hello world' 
}; 

request.post({ 
      headers: { 'content-type': 'application/x-www-form-urlencoded' }, 
      url: "url/test", 
      body: JSON.stringify(data) 
     }, function (error, response, body) { 

      logger.debug("error : ", error); 
      logger.debug("body : ", body); 

     }); 

聽一個明確的項目

app.post('/test', function(req, res) { 

    try { 
     res.header('Access-Control-Allow-Origin', req.headers.origin || "*"); 
     res.header('Access-Control-Allow-Methods', 'POST'); 
     res.header('Access-Control-Allow-Headers', 'Content-Type'); 

     console.log(req.body); 
     var x = JSON.parse(req.body); 

     res.send(200); 

    } catch (error) { 

     res.send(200); 
    } 
}); 

req.body是

{ '{ 「用戶」:{ 「ID」:123}, 「文本」: 「世界你好」}' : ''}

erorr是

語法錯誤:意外標記○在JSON位置1處

節拍額外單引號{「{ 「用戶」:{ 「ID」:123}, 「文本」: 「世界你好」 }':''}

+0

我認爲它同樣的問題,這個問題 http://stackoverflow.com/questions/10005939 /如何用消費 - JSON-後的數據中,一個快車的應用程序基本上,你需要bodyParser解析JSON身體 – PunNeng

+0

感謝punneng但bodyparse是我的代碼 – anotherbuild

回答

0

req.body是一個對象,不是一個簡單的字符串。 Javascript解釋器已經解析了它。這就是爲什麼你看到神祕的Unexpected token o in JSON at position 1消息,儘管JSON中沒有「o」; JSON.parse正在嘗試對非字符串進行字符串操作。

0

你應該增加一些選項,您的快遞應用程序配置和安裝使用npm install body-parser這樣身體的解析器包:

var bodyParser = require('body-parser'); 
app.use(bodyParser.json({ 
keepExtensions: true 
})); 
app.use(bodyParser.urlencoded()); 
+0

我一直在嘗試這樣 // Body Parser app.use(bodyParser.json()); //支持JSON編碼機構 app.use(bodyParser.urlencoded({ //支持URL編碼機構 擴展:真 })); //正文分析器結束 我會嘗試你的方法。我寫導致 – anotherbuild

+0

抱歉沒有變化:( – anotherbuild

+0

使用'JSON.parse(JSON.stringify((req.body))'到解析JSON值 – farhadamjady