I have Googled this problem over and over and can’t seem to find the solution.
Here is my frontend code:
export const getBlog = (sortColumn, sortOrder) => async dispatch => {
console.log("blogActions.js => getBlog() executed.");
console.log("sortColumn = " + sortColumn);
console.log("sortOrder = " + sortOrder);
let options = {
order: [sortColumn, sortOrder]
};
try{
// call the api. Get all our feedback from our endpoint.
const res = await axios.get('/api/blog', options
/*
{
params: {
sortColumn: "Heading",
sortOrder: "ASC"
}
} */
);
Here is my backend code:
router.get('/', async (req, res) => {
console.log('/api/blog - get');
// Return all blog.
// We need to query our database to get our data.
// We will do this by using the findAll() function, to get all the feedback in the feedbacks table.
// Note: Remember if we use await, we need an async before(req, res).
console.log("req.query = " + req.query);
console.log("req.params = " + req.params);
//const { sortColumn, sortOrder} = req.params;
const { sortColumn, sortOrder} = req.query;
console.log(sortColumn);
console.log(sortOrder);
try{
const list = await Blog.findAll(
/*
{
order: [[sequelize.col(sortColumn)]]
}
*/
);
// send the list back to the client.
res.send(list);
}
catch(e)
{
console.log(e); // error
}
});
The req.query and req.params on the backend both result in "undefined".
Any ideas how to solve this problem?
Kind Regards,
John
Melbourne, Australia
This is the debugging output on the server when requesting data from the frontend client:
frontend request, VS Code server console
I have tried using Postman and the params get passed through just fine, as you can see here:
Postman
2
Answers
The Axios option for URL query parameters is
params
…See Axios – Request Config
If you expect to receive
sortColumn
andsortOrder
params inreq.query
, you’ll need to construct your options like thisA word of warning though, some versions of Axios have a bug around URL query serialisation. I would always recommend using the Fetch API instead of Axios.
If you wanted to use
req.params
, you’d need to define your route with route parametersand send the request like this
I would not recommend this method for this type of request.
try change your axios get to this, the req query should be there in req.query