Node.js:如何使用url参数解析来自get请求的解析后的json对象

时间:2018-12-01 09:28:17

标签: javascript node.js json

我是后端和node.js的新手。我尝试使用帖子中的URL参数解析现有JSON数据后,使用JSON对象响应“ GET”帖子。

这是“ 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,因为当consolelog时const queryValue显示为“ Volume”。但是,在仅包含具有“ Volume”匹配值的对象的filter方法之后,我无法获得正确的JSON响应。

简而言之,我正在尝试获取一个具有data [0]和data [1]的所有属性的JSON对象响应。

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

2 个答案:

答案 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)));

答案 1 :(得分:0)

在@ aritra-chakraborty的答案之上,queryData是您需要传递queryValue的函数,可以通过执行以下操作来固定它:

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

... axios返回一个Promise,其中包含它自己的响应对象,而不是直接返回数据。您可以在此响应对象的data属性内访问您的响应数据。

所以您需要像这样修复它:

axios.get('http://localhost:3003/?name=Volume').then(data => {
  this.setState({
    searches: data.data
  });
}).catch(err => {
  console.log('Error happened during GET!', err);
});

...或者这样做

axios.get('http://localhost:3003/?name=Volume').then({data} => { 
  this.setState({
    searches: data
  });
}).catch(err => {
  console.log('Error happened during GET!', err);
});

了解更多:https://github.com/axios/axios