【问题标题】:JSON response getting cutoffJSON 响应被截断
【发布时间】:2017-08-24 23:06:33
【问题描述】:

制作了一个快速服务器来调用一个api。我们已经成功地在我们的服务器中请求 JSON 对象。我们现在的问题是让它在客户端显示为一个完整的 JSON 对象。当服务器从 api 请求时,json 数据被截断。有什么建议么?我尝试使用 parse 而不是 stringify 但收到此错误。

SyntaxError:JSON 输入意外结束
在 Object.parse(本机)
在 fetch.then.x (/Users/server.js:26:19)
在 process._tickCallback (internal/process/next_tick.js:103:7)

这是带有 stringify 的服务器代码。

var express = require('express');
var fetch = require('node-fetch');
var cors = require('cors');
const util = require('util');
const app = express();
var inflate = require('inflation')
var raw     = require('raw-body')
const json = require('body-parser').json();

app.use(cors())

const PORT = 3001
app.listen(PORT, () => {
  console.log(`Express server is running on port: ${PORT}!`);
});

app.get('/foo', (req,res) => {
  let dataUrl = 'www.apiURL.com/data.json';
  fetch(dataUrl)
  .then(x => {
    console.log(x.body._readableState.buffer.head.data.toString())
    let decompressed = inflate(x.body._readableState.buffer.toString());
res.send(JSON.stringify(x.body._readableState.buffer.head.data.toString()));
  })
  .catch(err => console.log(err))
})

这是客户端代码。

  componentDidMount(){
fetch(serverUrl)
.then(res => {
  res.json()
  .then(body => {
    this.setState({
      clubData: body
    })
    console.log(res)
  });
})
.catch(err => console.log(err))

为什么数据会被截断?字符串形式时无所谓,因为缓冲区也被切断了。

【问题讨论】:

    标签: javascript json reactjs express


    【解决方案1】:

    您的客户端代码应如下所示。

    componentDidMount(){
      fetch(serverUrl)
       .then(res => res.json())
       .then(body => 
         this.setState({
           clubData: body
         }))
       .catch(err => console.log(err))
    }
    

    如果这能解决您的问题,请告诉我,如果还有其他我遗漏的内容,我可以更新答案

    【讨论】:

    • 谢谢罗兰!我得到了同样的回应。无法弄清楚为什么 JSON 被切断了!
    • 能否将console.log同时放在服务器和客户端,并用结果更新问题?
    猜你喜欢
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 2014-08-13
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多