Express 服务器响应是一个流,如何使它成为一个字符串 / json

Express server response is a stream, how to make it a string / json

我正在 POST 将数据发送到我的 express (v.4+) 服务器。但是,我在浏览器中得到的响应是这样的:

Response {type: "cors", url: "http://localhost:1111/", status: 200, ok: true, …}

具体来说,响应的 bodyReadbleStream,而不是我发回的响应所期望的 jsonstring

服务器代码是:

mongoose.connect('mongodb://localhost/block');
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', (req, res, next) => { // for cors
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Credentials', true);
  next();
});

app.post('/', (req, res) => {
  const { dataType, table } = req.body;
  const { rows } = table;
  const log = {
    msgArray: []
  };
  function saveData(dbModel) {
    rows.forEach(row => {
      row.data_initiated = new Date();
      row.status = 'initiated';
      const entry = new dbModel(row);
      entry.save(err => {
        if (err) {
          log.msgArray.push({ err });
        }
        log.msgArray.push({
          msg: 'saved!'
        });
      });
    });
  }
  if (dataType === 'Contract') {
    saveData(Contract);
  } else if (dataType === 'Commodity') {
    saveData(Commodity);
  } else {
    saveData(Client);
  }
  res.send(log).end();

我在客户端使用 fetchPOST 数据。

我怎样才能更正发送 json / string 给用户?

谢谢,

使用fetch时,必须将响应转换为JSON,然后返回。在随后的then中,可以使用转换后的值。

fetch( url, config)
  .then( res => res.json())
  .then( json => {
    console.log( json );
    ...
  }

值得一提的是,这与我们在使用 Axios.js(基于承诺的 AJAX 库)时处理响应的方式有点不同。

P.S:我更新了问题以修复代码,以便正确发送响应。