Reputation: 169
I'm trying to create a search feature, but when I try to pass data (params
) to the back end with an axios.get
request, it is showing undefined
.
My react app request handling function:
handleSearch() {
API.search(this.state.searchType, this.state.searchValue)
.then(response => { 1 }).catch(error => console.log(error));
}
The above seems to work perfectly as far as I can tell. Those state values are valid and I did test that they were defined
at this point.
My axios/API function:
search: function(searT, searV) {
let searchData = {
'searchType': searT,
'searchValue': searV
};
return axios.get('/search', searchData).then(response => 1);
}
The above appears to be correct according to the axios docs
and every other resource I've found. The searT
and searV
values are passed to this point successfully.
Back end express
function:
app.get('/search', function(request, response) {
let {searchType, searchValue} = request.params;
console.log('SearchType: ' + searchType + ' and SearchValue: ' + searchValue); //both return undefined
});
searchType
and searchValue
are undefined
here, what the heck?!
I've seen plenty of similar issues out there, but none seem to help me solve this issue. I am wondering if it's something to do with my server.js
file, but my axios.post
requests work fine.
I feel like this will be my derp of the week after I figure it out, but for now it's killing me.
What solved this question, thanks to Montgomery and react-node:
return axios.get('/search', { params: searchData }).then(response => 1);
app.get('/search', function(request, response) {
let {searchType, searchValue} = request.query;
});
Upvotes: 0
Views: 2187
Reputation: 4034
searchType
and searchValue
are getting passed in the query string, so it's necessary to access them with request.query
.
As pointed out by @react-node, the data was also being passed incorrectly to the axios.get
call. To correctly pass the query string parameters with axios.get
, it needs to look like this:
return axios.get('/search', {
params: searchData
}).then(response => 1);
Upvotes: 1
Reputation: 31
just change
return axios.get('/search', searchData).then(response => 1);
to
return axios.get('/search', {params:searchData}).then(response => 1);
and on the server-side you should change request.params
to request.query
Upvotes: 3