Reputation: 1
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.
Upvotes: 0
Views: 789
Reputation: 1721
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
Upvotes: 0
Reputation: 12542
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)));
Upvotes: 1