javascript - Node.js:如何使用 url 参数从获取请求解析后响应 json 对象
问题描述
我是后端和 node.js 的新手。在使用帖子中的 URL 参数解析现有 JSON 数据后,我正在尝试使用 JSON 对象响应“GET”帖子。
这是“获取”帖子
search.js
componentDidMount() {
axios
.get('http://localhost:3003/?name=Volume')
.then(data => {
this.setState({ searches: data });
})
.catch(err => {
console.log('Error happened during GET!', err);
});
}
这是外部 JSON 数据文件
data.js
var data = [
{
"id": "01",
"name": "Damage Reverse Oil Conditioner",
"tags": [
"green",
"conditioner"
]
},
{
"id": "02",
"name": "Volume Advance 1",
"tags": [
"blue",
"conditioner"
]
},
{
"id": "03",
"name": "Volume Advance 2",
"tags": [
"red",
"shampoo"
]
}
];
这是需要 data.js 文件的 node.js 文件
app.js
const data = require('./data');
const http = require('http');
const url = require('url');
const hostname = 'localhost';
const port = 3003;
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
const queryValue = url.parse(req.url,true).query.name;
const queryData = (query) => {
return data.filter((el) =>
el.toLowerCase().indexOf(query.toLowerCase()) > -1
);
}
res.end(JSON.stringify(queryData(queryValue)));
}).listen( port );
console.log(`[Server running on ${hostname}:${port}]`);
我能够解析参数的 url,因为 const queryValue 在控制台日志中显示为“Volume”。但是,在仅包含具有“Volume”匹配值的对象的过滤方法之后,我无法获得正确的 JSON 响应。
简而言之,我试图获得一个 JSON 对象响应,它具有数据 [0] 和数据 [1] 的所有属性。
任何帮助/建议将不胜感激。谢谢。
解决方案
乍一看,我可以看到
const queryData = (query) => {
return data.filter((el) =>
el.toLowerCase().indexOf(query.toLowerCase()) > -1
);
}
这是一个功能。所以,而不是res.end(JSON.stringify(queryData));
你需要做
res.end(JSON.stringify(queryData(queryValue)));
推荐阅读
- c# - 将这些方法从 EF 6 转换为 EF Core
- angularjs - 如何刷新 angularJS 项目的 index.htm?
- vue.js - 如何渲染一个 tag as an actual DOM element?
I'm currently working on a script that uses
<template>
tags for obtaining markup th- java - Freemarker 自定义字符转义(转义 LaTeX 特殊字符)
- vb.net - 如何设置组合的数据源并在加载时设置文本值
- javascript - JS数组显然没有长度
- python-3.x - 如何使用 python 曲线拟合这个特定的数据图?
- javascript - 我可以将 img 的 src 更改为视频 src 并返回吗?
- session - rails session object server端的哪些部分实际写入用户的session cokie
- rest - java.util.ServiceConfigurationError: org.apache.juli.logging.Log: 提供者 org.eclipse.jetty.apache.jsp.JuliLog 不是子类型