I am trying to allow a user to enter their name and have it added to the URL.
for example if the users input is John it redirects the user to "/profile/John"
So far I have tried to define a variable name from the parsed input from my html form.
html code;
<h4>Search for your profile by entering your name below.</h4>
<form action="/" method="post">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit" name="button">Search</button>
</form>
Node code;
app.get('/',function(req,res){
var name = String(req.body.name);
});
app.post("/profile/:" name, (req,res)=>{
var data = {
age: 19,
job: 'Student',
hobbies: ['Fishing','Video games','Anime','Basketball']
};
res.render('profile',{name: req.params.name, data: data});
});
But I get this error;
^
app.get('/profile/:' name, (req,res)=>{
^
ReferenceError: name is not defined
CodePudding user response:
you need to put name inside the path quotes, like this
app.get('/profile/:name',(req,res) =>{ }
the : after / indicates that the next value is dynamic
check out ExpressJS - URL Building
CodePudding user response:
app.get('/',function(req,res){
// var name = String(req.body.name);
});
Above is not necessary part. You should handle like below
app.post("/profile/:name", (req,res)=>{
var name = String(req.params.name)
var data = {
age: 19,
job: 'Student',
hobbies: ['Fishing','Video games','Anime','Basketball']
};
res.render('profile',{name: req.params.name, data: data});
});
You can check the details in this question