[英]POST data using node.js
I'm trying to get form data to node server using POST method. 我正在尝试使用POST方法将表单数据获取到节点服务器。 This is my HTML code, 这是我的HTML代码,
<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 这是我的节点应用程序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. 将这些行添加到您的app.js中。
require body-parser. 需要身体分析器。
var bodyParser = require('body-parser');
put before your first app.get that will be better. 放在您的第一个app.get之前会更好。
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. Express默认情况下不解析请求正文,您将必须使用中间件来执行该操作。
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. 它解释了一些与通用主体解析方法有关的问题(及其解决方案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.