首页 > 解决方案 > Express 不发送 JSON,但可以正常发送其他字符串

问题描述

这是代码:

res.status(400).send('{"test":1}');

这将返回一个空响应。这将返回“测试”:

res.status(400).send('test');

这是我正在使用的唯一扩展:

app.use(bodyParser.json({ limit: '50mb', type: 'application/*' }));

如何让 Express 发送 JSON?我正在使用 Express 4.16.3(最新版本)。

编辑,这是整个文件。我使用 Express 作为代理:

const express = require('express');
const path = require('path');
const qs = require('qs');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');

const API_URL = 'https://api.example.com/';

const app = express();
app.set('json spaces', 2);
Error.stackTraceLimit = 100;
app.use(bodyParser.json({ limit: '50mb', type: 'application/*' }));

app.options(/\/api\/(.+)/, async (req, res) => {
  res.writeHead(200, {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Credentials': false,
    'Access-Control-Max-Age': '86400',
    'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept',
  });
  res.end();
});

app.all(/\/api\/(.+)/, async (req, res) => {
  let url = API_URL + req.params[0];
  if (Object.keys(req.query).length) {
    url += `?${qs.stringify(req.query)}`;
  }

  const opts = {
    method: req.method,
    headers: {
      'content-type': req.headers['content-type'] || 'application/json',
    },
  };
  if (req.headers.authorization) {
    opts.headers.authorization = req.headers.authorization;
  }
  if (req.method.toUpperCase() !== 'GET') {
    opts.body = JSON.stringify(req.body);
  }

  res.setHeader('content-type', 'application/json');
  try {
    const result = await fetch(url, opts);
    const data = await result.text();
    res.status(result.status).send({"test":1});
  } catch (err) {
    res.status(500).send(err.message || err);
  }
});

app.listen(9002, () => console.log('Server started.'));

标签: node.jsexpress

解决方案


这是一个 CORS 问题。添加后它起作用了:

  res.header('access-control-allow-origin', '*');
  res.header('access-control-allow-headers', 'origin, x-requested-with, content-type, accept');

我不知道为什么它与非 JSON 字符串一起工作,但如果响应是 JSON,它就会被阻止。


推荐阅读