skip to Main Content

Problem:

I have created an email verification function when a user is registered. I send link to backend method URL with a hash code like this.

let link = `http://localhost:3000/api/user/verify?id=${
     user[0].hash
}`;
let info = await smtpTrans.sendMail({
    from: '"Welcom" <[email protected]>',
    to: req.body.email,
    subject: "Please confirm your Email account",
    html: "Hi!,<br> Please Click on the link to verify your email.<br><a href=" +link +">Click here to verify</a>.<br> Thank you for registering with mysite.lk!.<br> mysite.lk Team"

This is my particular verification method where I point my link.

router.post("/verify/:id", (req, res) => {
  res.redirect("https://www.facebook.com/");
});

For testing purpose, I just redirect to facebook.

The email is successfully sending but when I click the link in the mail. It says

Cannot GET /api/user/verify

Can someone help me to solve this issue? I tried a lot to find a solution to this problem but I was unable to do so. Thank you.

2

Answers


  1. You have to use GET instead of POST in

    router.get("/verify/:id", (req, res) => {
      res.redirect("https://www.facebook.com/");
    });
    

    When a user clicks your link inside the email (or whenever you type any URL in the address bar of a browser), the browser is asked to open the said link. The default action of the browser is to request the link using GET method and not POST.

    POST is only applicable when you can define how the HTTP request is to be initiated, which in the context of the browser is either using javascript after the page loads or submitting a form and explicitly specifying POST as the method.

    Login or Signup to reply.
  2. The problem is in the http request method and in your route path. What I mean?

    1. When you click this link http://localhost:3000/api/user/verify?id=a-users-hash for example, you send a GET request in Node Server. So you have to define a GET method to handle the request.
    2. In this link, id is a query marameter. In case you want to access id value you have to use req.query object instead of req.params.

    The point here is that the path where you handle this request should be /api/user/verify or /verify depending the middleware you have defined.

    /verify/:id will NOT catch your request because as i said before id is a query parameter.

    So your method should be like this:

    router.get("/verify", (req, res) => {
      // req.query.id is your id hash.
      res.redirect("https://www.facebook.com/");
    });
    

    If you want to use this router.get("/verify/:id", (req, res) approach, your link should have this http://localhost:3000/api/user/verify/hashId form.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search