skip to Main Content

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


  1. You are mixing up two different concepts.

    Route parameters are defined with router.put('/post/:user_id/:id', sent in the URL with http://example.com/post/myUserId/myid/ and appear in req.params.

    A query string is not defined in the route (router.put('/post/',, sent in the URL with http://example.com/post/?user_id=myUserId&id=myid and appear in req.query.

    Login or Signup to reply.
  2. 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

    router.put('/post/:user_id/:id', updatePost);
    
    async updatePost(req, res) {
      try {
        const id = req.id
        const user_id = req.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'
        })
      }
    
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search