簡體   English   中英

使用node.js發布數據

[英]POST data using node.js

我正在嘗試使用POST方法將表單數據獲取到節點服務器。 這是我的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>

這是我的節點應用程序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');
});

現在,當我單擊“提交”時,將收到如下錯誤消息,

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

如何將輸入的名稱打印到控制台?

將這些行添加到您的app.js中。

需要身體分析器。

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

放在您的第一個app.get之前會更好。

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

祝好運。

Express默認情況下不解析請求正文,您將必須使用中間件來執行該操作。

嘗試這個。

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

...
...

另外,您應該閱讀這篇文章 它解釋了一些與通用主體解析方法有關的問題(及其解決方案)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM