如何让Node.js的res.send返回数组而非字符串,前端可直接使用?
问题解答
服务端返回逻辑
你完全可以直接用res.send()返回数组类型数据,不需要额外处理:
Express 内置了JSON序列化能力,当res.send()接收的参数是数组或普通对象时,会自动执行以下操作:
- 调用
JSON.stringify()把数组/对象转为JSON格式字符串 - 自动设置响应头
Content-Type: application/json,告知前端返回的是JSON格式数据
你现在写的服务端代码逻辑是正确的,已经可以正常返回你需要的二维数组格式的响应内容。
前端代码问题
你现在前端拿到的不是数组,是因为没有对返回的JSON数据做解析,XMLHttpRequest默认返回的是纯字符串格式的响应内容,有两种修改方案:
方案1:让浏览器自动解析JSON
在调用xhttp.open()之前添加responseType配置即可:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { // 增加请求完成和成功状态判断,避免请求未完成/失败时执行逻辑 if (this.readyState == 4 && this.status == 200) { const clothes = this.response; // 这里已经是解析完成的二维数组 console.log(Array.isArray(clothes)); // 输出true,可确认是数组类型 document.getElementById("demo").innerHTML = JSON.stringify(clothes); } }; xhttp.open("GET", "http://localhost:3000/post", true); xhttp.responseType = 'json'; // 加这行指定响应类型为JSON,浏览器会自动完成解析 xhttp.send();
方案2:手动解析返回的JSON字符串
如果不方便设置responseType,也可以在回调里手动转换:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const clothes = JSON.parse(this.response); // 手动把JSON字符串转成JS数组 document.getElementById("demo").innerHTML = JSON.stringify(clothes); } }; xhttp.open("GET", "http://localhost:3000/post", true); xhttp.send();
内容的提问来源于stack exchange,提问作者Em Maclean
相关产品推荐
相关产品推荐

