我正在尝试将表格数据从html页面传送到Node Js服务器。
我的html文件是 index.html
<body>
<nav>
<ul>
<li>
<a href="#" class="button add">Add Product</a>
<div class="dialog" style="display:none">
<div class="title">Add Product</div>
<form action="" method="get">
<input id = "name" name="name" type="text" placeholder="Product Name"/>
<input name="code" type="text" placeholder="Product Code"/>
<input name="category" type="text" placeholder=" Category"/>
<input name="brand" type="text" placeholder="Brand"/>
<input type="submit" value="Ok"/>
</form>
</div>
</li>
<li class="radio">
<a href="#" class="button active"></a>
<a href="#" class="button"></a>
<a href="#" class="button"></a>
</li>
</ul>
</div>
</nav>
<p></p>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
提交表单后,服务器没有执行任何操作只需获取包含所有详细信息的网址
我的服务器是 server.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
methodOverride = require('method-override'),
hostname = process.env.HOSTNAME || 'localhost',
port = parseInt(process.env.PORT, 10) || 4004,
publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
//Show homepage
app.get("/", function (req, res) {
res.redirect("/index.html");
console.log("shubh ");
});
app.get("/index/", function (req, res) {
res.redirect("/index.html");
console.log("shubham ");
});
app.get("/index/:name", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.body.name + '".');
console.log(res.body);
});
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);
答案 0 :(得分:1)
您的表单操作是&#39;&#39;因此,表单创建的URL将是 /?name = xxx&amp; code = yyy etc
从您的路由中,您似乎期望网址为/ xxx?code = yyy。
进行表单操作&#39; / search&#39;并添加以下JS。
app.get("/search", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.query.name + '".');
});
当你提出请求时,request.body不会被设置。
答案 1 :(得分:0)
您可以根据需要使用多个:
var code = req.query.code;
var category = req.query.category;
var brand = req.query.brand;
req.query
如果是GET请求,req.body
是否为POST。
答案 2 :(得分:0)
更改app.get("/index/:name", function (req, res){
到app.get("/index/:name?", function (req, res){
你的路线将匹配/ index /和/ index / anyname routes
并将表单操作更改为"/"
或类似"/action"