I have a database which has the following structure. I need to write a request that will issue a post, by user_id and id.
id | title | content | user_id
----+----------------------------+-----------------------------+---------
This is the route I tried but it doesn’t work.
router.put('/post/:user_id&id', updatePost);
This is a controller, I do not understand how to correctly pass data for a correct request to the Database
async updatePost(req, res) {
try {
const id = req.query.id
const user_id = req.query.user_id
const {title, content} = req.body
const updatePost = await db.query(`UPDATE post SET title = $1, content = $2 WHERE id = $3 AND user_id = $4`, [title, content, id, user_id])
res.json(updatePost.rows)
} catch (err) {
console.log('Error when update a post:', err)
res.status(500).json({error: 'Something went wrong, try again later. Res status - 500'})
}
}
I also try next route
router.put('/post/:user_id/:id', updatePost);
// But I don't understand how the controller takes the data for user_id and id
2
Answers
You are mixing up two different concepts.
Route parameters are defined with
router.put('/post/:user_id/:id'
, sent in the URL withhttp://example.com/post/myUserId/myid/
and appear inreq.params
.A query string is not defined in the route (
router.put('/post/',
, sent in the URL withhttp://example.com/post/?user_id=myUserId&id=myid
and appear inreq.query
.Basically what Quentin has answered. Express on node is quite helpful and easy system to build on top of.
You should decide how you would like to structure this route, query parameters or route parameters.
this is an answer for route parameters