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
You have to use GET instead of POST in
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.
The problem is in the http request method and in your route path. What I mean?
http://localhost:3000/api/user/verify?id=a-users-hash
for example, you send aGET
request in Node Server. So you have to define aGET
method to handle the request.id
is aquery marameter
. In case you want to access id value you have to usereq.query
object instead ofreq.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:
If you want to use this
router.get("/verify/:id", (req, res)
approach, your link should have thishttp://localhost:3000/api/user/verify/hashId
form.