简体   繁体   中英

Node.js : How to respond with json object after parse from get request with url params

I am new to the backend and node.js. I am trying to respond to a "GET" post with a JSON object after parsing the existing JSON data with the URL parameters from the post.

Here is the "GET" post

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);
  });
}

This is the external JSON data file

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"
    ]
}
];

Here is the node.js file that is requiring the data.js file

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}]`);

I'm able to parse the url for the params since the const queryValue shows up as "Volume" when consolelog. However, I unable to get the proper JSON response after the filter method that contains only the objects that has matching value of "Volume".

In short I am trying to get a JSON object response that has all the properties of data[0] and data[1].

Any help/ advice will be greatly appreciated. Thanks.

At first glance I can see that

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

this is a function. So, instead of res.end(JSON.stringify(queryData)); you need to do

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

On top of @aritra-chakraborty's answer, that queryData is a function which you need to pass queryValue which can be fixed by doing:

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

... axios returns a Promise containing it's own response object instead of returning data directly. Your response data is accessible inside the data property of this response object.

So you need to either fix it like this:

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

...Or do this

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

Read more: https://github.com/axios/axios

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM