I am totally newbie to JavaScript and Express. Now I am trying to build a route to check whether the user's name has already been saved as a cookie in the server if no then the user can fill the form and send it to the server. The name which the user sent would appear in URL and I can use req.query to get the name from http://localhost:3000/trackName?name=aaa, save it to cookie, redirect to the checking page, and print it on site, done.
However, now I have stuck in the "The name which the user sent would appear in URL and I can use req.query to get it and save it to cookie" part, because my program never gets to the second "get" function in my code, I can print out the name I get in the first "get", but the second part would never run in the console, neither the browser.
Here is my code:
router.get('/myName', (req, res) => {
const name = req.cookies.username;
if (name) {
console.log(name);
res.render('myName', {name: name});
} else {
console.log("else");
res.render('myName');
}
});
router.post('/myName', (req, res) => {
res.redirect('/trackName');
});
router.get('/trackName', (req, res) => {
console.log(req.query.name); // here I can print out the name I got from form in terminal 'aaa'
return res.render('trackName');
});
router.get('/:id', (req, res) => {
console.log(req.query.name); // This part never appeared in terminal
res.cookie('name', req.query.name);
res.redirect('/myName');
})
router.post('/goodbye', (req, res) => {
res.clearCookie('name');
res.redirect('/myName');
});
Also, here is my pug form for getting name:
doctype html
html(lang="en")
head
title My Server
body
block content
if name
h2 username: #{name}
form(action='/goodbye', method='post')
button(type='submit') Goodbye
else
form(action='/trackName', method='get')
label Please enter your name:
input(type='text', name='name')
button(type='submit') Submit
Have tried fiddling around for a long while but still failed... Could somebody help me some keywords or methods to search?
Update:
I tried @jfriend00 's suggestion to modify the /trackName to /name in my HTML form in order to make router.get('/:id', ... run, but now I got URL http://localhost:3000/name?name=aaa which is not I want, and still the router.get('/:id', ... doesn't get the query either...