2015-01-03 42 views
0

我正在使用node.js进行基本的表单处理任务。阅读html文件输入并发送到node.js进行处理

加载html文件,但是当我提交表单时,它无法处理。

这里是我现在正在运行的代码:

formhandling2.js

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 

app.get('/', function(req, res){ 
res.sendfile('peanuts.html'); 

app.post('/myaction', function(req, res){ 
var userName = req.body.userName; 
res.send ('Hello: ' + userName + '.<br>' + '<a href="/">Try again.</a>'); 
res.sendfile('peanuts.html'); 
}); 

app.listen(80); 

peanuts.html

<html> 
    <head> 
     <title>Forms></title> 
    </head> 
    <body> 
     form action="/myaction" method="post"> 
     <p>Enter your name:</p> 
     <input type="text" name="userName" placeholder="..." /> 
     <br> 
     <button type="submit">Submit</button> 
    </body> 
</html> 
+0

为什么你有一个无效的HTML文件? (peanuts.html) –

+0

“无法处理”是什么意思?错误信息还是什么? – mscdex

回答

0

你有一个语法错误,你的服务器文件

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 

app.get('/', function(req, res){ 
res.sendfile('peanuts.html'); 
}) 
app.post('/myaction', function(req, res){ 
var userName = req.body.userName; 
res.send ('Hello: ' + userName + '.<br>' + '<a href="/">Try again.</a>'); 
res.sendfile('peanuts.html'); 
}); 

app.listen(80); 

请参阅上文,在res.sendfile('peanuts.html')之后,您必须关闭})括号。

那么你有html语法错误你还没有开始形式标记。下面

<html> 
    <head> 
     <title>Forms></title> 
    </head> 
    <body> 
     <form action="/myaction" method="post"> 
     <p>Enter your name:</p> 
     <input type="text" name="userName" placeholder="..." /> 
     <br> 
     <button type="submit">Submit</button> 
    </body> 
</html> 

一切正确的代码工作不错,我测试一次固定