无法使用Express发布/出错 [英] Cannot POST / error using express
本文介绍了无法使用Express发布/出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用express创建一个简单的表单处理程序.我为表单尝试了以下代码:
I am trying to create a simple form handler using express. I tried the code below for my form:
<form class="form" action="/" method="post" name="regForm">
<div class="form-group">
<input type="text" name="username" class="form-control" id="username" placeholder="Username">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
这是我的app.js代码:
And here is my app.js code:
const port = 3000;
var express = require('express'),
app = express(),
server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({
extended: true;
}));
app.use(bodyParser.json());
app.post('/',function(req,res){
var username = req.body.username;
var html = 'Hello:' + username;
res.send(html);
console.log(html);
});
server.listen(port);
提交表单后,我仍然收到错误消息"CANNOT POST/".我是否缺少类似模块的内容?
I keep getting the error "CANNOT POST /" after submitting the form. Am I missing something like a module?
推荐答案
这种方式您应该尝试
const port = 3000;
var express = require('express'),
app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.render('form');// if jade
// You should use one of line depending on type of frontend you are with
res.sendFile(__dirname + '/form.html'); //if html file is root directory
res.sendFile("index.html"); //if html file is within public directory
});
app.post('/',function(req,res){
var username = req.body.username;
var htmlData = 'Hello:' + username;
res.send(htmlData);
console.log(htmlData);
});
app.listen(port);
将来参考时应注意的事项:
- 您将url编码扩展为true
- 您没有要求获取表格的请求
- 您正在使用HTML命名变量,这是一种不良做法
感谢&干杯
这篇关于无法使用Express发布/出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文