node.js - 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.'));
解决方案
这是一个 CORS 问题。添加后它起作用了:
res.header('access-control-allow-origin', '*');
res.header('access-control-allow-headers', 'origin, x-requested-with, content-type, accept');
我不知道为什么它与非 JSON 字符串一起工作,但如果响应是 JSON,它就会被阻止。
推荐阅读
- docker - Docker`COPY`文件不起作用
- python-3.x - 逐行读取和分析输出数据
- batch-file - Sqlcmd 参数传递给 sql 脚本文件
- java - 如何制作自定义文本视图?
- c# - 使用 mshtml 和 shdocview vb.net/C# 捕获 Web 元素
- php - 在 Laravel-5 中取消定义方法?
- selenium - 在另一个选项卡中打开相同的 URL 时,Selenium 未显示活动会话被拒绝
- node.js - 在 ejs 模板中获取查询字符串
- c# - 授权 - .net 核心中的声明集
- amazon-web-services - Ruby AWS 开发工具包 (v2/v3) 标记 Spot 实例