0

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.

  • Possible duplicate of [Proper way to return JSON using node or Express](https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express) – Matteo Meil Dec 01 '18 at 09:37
  • So I don't see anything really wrong with your back-end code. But I see you're using `axios` incorrectly. You'll want something like `axios.get(url).then(response => response.data)` to get the data as `axios` doesn't return the data in its Promise directly so you need to access the `data` property. Read more: https://github.com/axios/axios – ionizer Dec 01 '18 at 19:06

2 Answers2

1

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)));
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
0

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

ionizer
  • 1,661
  • 9
  • 22