首页 > 解决方案 > 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] 的所有属性。

任何帮助/建议将不胜感激。谢谢。

标签: javascriptnode.jsjson

解决方案


乍一看,我可以看到

const queryData = (query) => {
    return data.filter((el) =>
      el.toLowerCase().indexOf(query.toLowerCase()) > -1
    );
  }

这是一个功能。所以,而不是res.end(JSON.stringify(queryData));你需要做

res.end(JSON.stringify(queryData(queryValue)));

推荐阅读