Search code examples
javascriptxmlhttprequestbcrypt

How to add params to request in get request xmlhttprequest


Currently, I am trying to use the bcrypt module to compare the hashed password in the db to the password in the request params. My code for the backend is:

router.get('/:username', getAcc, async (req, res) => {
    const user = await Account.find(req.body.username)
    console.log(req.password)
    const check = bcrypt.compare(password, user[0].password);
    if (check == false) return res.json('Incorrect Password');
    res.json(res.acc)
})

And I do request by:

  const url = `http://localhost:3000/config/${username}`
  const request = new XMLHttpRequest()
  request.open("GET", url+"?password="+password, true);
  request.send()
  request.onload = function(){
      let jsonResponse = `${request.response}`;
      if (jsonResponse == 'Invalid password') return alert('Invalid password');
      alert(jsonResponse)
      let parsedRes = JSON.parse(jsonResponse);
  }

Now I want to add a password field to this, either via req.password or a different field, and be able to send a request with the password paramater. Is this possible, and how to do it?


Solution

  • You should not be putting a user's password in the request URL, instead you should put it in the request headers. The reason for this is because putting passwords, and other sensitive information in the headers is considered more secure and safer.

    To do exactly what you want but using headers, use the following code for the client side (I have included comments for the lines changed):

    const url = `http://localhost:3000/config/${username}`
    const request = new XMLHttpRequest()
    request.open("GET", url, true); // Got rid of '+ "?password=' part
    request.setRequestHeader('password', password) // This is the part where a new header is set
    request.send()
    request.onload = function(){
        let jsonResponse = `${request.response}`;
        if (jsonResponse == 'Invalid password') return alert('Invalid password');
        alert(jsonResponse)
        let parsedRes = JSON.parse(jsonResponse);
    }
    

    And use this for backend:

    router.get('/:username', getAcc, async (req, res) => {
        const user = await Account.find(
            req.body.username,
            req.headers['password'] // This will get the password from the headers
        )
        const check = bcrypt.compare(req.headers['password'], user[0].password); // Same thing - gets the password from headers
        if (check == false) return 'Incorrect Password'
        res.json(res.acc)
    })
    

    If you encounter any issues with my answer, feel free to leave a comment.