简体   繁体   中英

POST data using node.js

I'm trying to get form data to node server using POST method. This is my HTML code,

    <html>
    <head>
            <title>
                Node Architecture
            </title>
    </head>
<body>
    <h1>Node Architecture</h1>
    <h3>Enter Your name.</h3>
    <form action="/" method="POST">
    <input type="text" name="eventname" />
    <input type="submit" value="Go" />
</form>

</body>
</html>

This is my node app, index.js

var app = require('express')();
var http = require('http').Server(app);
//var io = require('socket.io')(http);
//var qs = require('querystring');

app.get('/', function(req, res){
  res.sendfile('index.html');
});
app.get('/events', function(req, res){
  res.sendfile('events.html');
});
app.get('/movie', function(req, res){
  res.sendfile('movie.html');
});

app.post('/', function(req, res) {
    var name = req.body.eventname;
    console.log(name);
});



http.listen(3000, function(){
  console.log('listening on *:3000');
});

Now when I click submit I get an error message which is as follows,

TypeError: Cannot read property 'eventname' of undefined at Object.handle 

How do I print the entered name to my console?

Add these lines into your app.js.

require body-parser.

var bodyParser = require('body-parser');

put before your first app.get that will be better.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

good luck.

Express doesn't parse request body by default, you will have to use a middleware to do that.

Try this.

var express = require('express');
var app = express()
    .use(express.bodyParser());

...
...

Also, you should read this article . It explains some of the problems (and their solutions) related to common body parsing approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM