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.