Express中转Axios请求JSONPlaceholder数据出现乱码,求解决
问题定位与解决
核心原因
乱码的本质是jsonplaceholder的接口返回了gzip/deflate压缩后的二进制数据,你转发时未做解压处理,直接把压缩数据返回给客户端,浏览器无法解析就显示乱码。而httpbin的接口未启用压缩,所以能正常显示。
具体解决方案
方案1:用成熟HTTP客户端简化转发(推荐)
用axios或got这类库,它们会自动处理响应编码、解压压缩数据,无需手动处理:
const express = require('express'); const axios = require('axios'); const app = express(); const PORT = 3031; // 转发httpbin/get app.get('/simpleget', async (req, res) => { try { const resp = await axios.get('https://httpbin.org/get'); res.json(resp.data); } catch (err) { res.status(500).send(err.message); } }); // 转发jsonplaceholder用户接口 app.get('/users/:id', async (req, res) => { try { const resp = await axios.get(`http://jsonplaceholder.typicode.com/users/${req.params.id}`); res.json(resp.data); } catch (err) { res.status(500).send(err.message); } }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
方案2:原生http模块手动处理压缩
如果坚持用Node.js原生http模块,需要通过zlib模块解压压缩数据:
const express = require('express'); const http = require('http'); const zlib = require('zlib'); const app = express(); const PORT = 3031; app.get('/users/:id', (req, res) => { http.get(`http://jsonplaceholder.typicode.com/users/${req.params.id}`, (upstreamResp) => { // 判断响应是否被压缩 const encoding = upstreamResp.headers['content-encoding']; let dataStream = upstreamResp; // 根据编码类型解压 if (encoding === 'gzip') { dataStream = upstreamResp.pipe(zlib.createGunzip()); } else if (encoding === 'deflate') { dataStream = upstreamResp.pipe(zlib.createInflate()); } // 转发解压后的数据,同步设置Content-Type res.setHeader('Content-Type', upstreamResp.headers['content-type']); dataStream.pipe(res); }).on('error', (err) => { res.status(500).send(err.message); }); }); // 转发httpbin/get的原生实现 app.get('/simpleget', (req, res) => { http.get('https://httpbin.org/get', (upstreamResp) => { upstreamResp.pipe(res); }); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
为什么你之前的尝试无效?
TextDecoder、JSON.stringify这类操作都是在处理字符串,但原始响应是压缩后的二进制字节流,直接转字符串只会把压缩字节解析成无意义的乱码字符。必须先完成解压,再处理内容。
内容的提问来源于stack exchange,提问作者Spade
相关产品推荐
相关产品推荐

