Reputation: 10551
i just red this post
my express Code is
var express= require('express');
var app= express();
var path= require('path');
app.use(express.static(path.join(__dirname,'public'))) //one way to server file
//app.use(express.static(__dirname,'/public'));
app.get('/',function(request, response){
response.send("responde send");
})
app.get('/userName',function(request, response){
response.send(request.query["userName"]);
})
app.post('/userName1',function(request,response){
response.send(request.body.userName);
console.log(request.body['userName']);
})
var server= app.listen(3001,function(){
var host = server.address().address
var port = server.address().port
console.log("listening "+port+ "port while the host"+host);
})
now handling get request using this code html is
<form action="/userName" method="get">
<input type="text" name="userName">
<input type="submit">
</form>
for post request my html is
<form action="/userName1" method="post">
<input type="text" name="userName">
<input type="submit">
</form>
but the problem how to get post request data?? i have tried these two line
response.send(request.body.userName);
console.log(request.body['userName']);
but not working while this link code is same where i am learning. Also inform me how to redirect user to any html file when user submit a form?
Upvotes: 0
Views: 2415
Reputation: 11
You have to use Like below
res.send("<script> window.location = 'http://localhost:8080'; </script>");
Above code is working for me. Hope also for you.
Upvotes: 0
Reputation: 66
what I use is Body-Parser with Express 4. So you need to assign Body-Parser to Express, and then, you can do something like:
app.post("userName1", function(req, res){
var username = req.body.userName;
});
Is in bold method used, path the information is sent, name of the input of the form sent respectively.
As for redirection, you can use: res.redirect("URL"), or:
res.send("<script> JAVASCRIPT REDIRECT CODE </script>")
Hope It works for you :)
Upvotes: 0
Reputation: 9260
That link is outdated. ExpressJS now uses body parser as a separate component, which is what you need in order to parse form data properly.
As for redirection, you could use javascript:
window.location = "https://www.google.com"
or, set the redirect header on the server:
res.setHeader("Location", "http://somewhere.com")
which is the same as:
res.location("http://somewhere.com")
Upvotes: 1