我想将html表单数据存储在JSON文件中,但出现错误。
“ TypeError:无法读取未定义的属性'Name'”
还要告诉我如何从字符串JSON创建json文件。以及如何从多个用户添加数据。
我的html文件是:
<!DOCTYPE html>
<html>
<head>
<title>Sign up</title>
<style type="text/css">
div {
background-color: rgb(66, 244, 229);
padding: 15px;
margin: auto;
width: 300px;
border-radius: 7px;
}
input {
width: 100%;
padding: 10px;
box-sizing: border-box;
}
input[type=submit] {
border-radius: 5px;
border: none;
margin: auto;
background-color: orange;
color: white;
}
</style>
</head>
<body>
<div>
<form action="/form" method="Post">
<input type="text" name="Name" placeholder="Enter your Name"><br>
<br>
<input type="email" name="Email" placeholder="Enter Email id"><br>
<br>
<input type="password" name="Password" placeholder="Set Password">
<br><br>
<input type="number" name="Mobile" placeholder="Enter mobile
number"><br><br>
<input type="submit" value="submit">
</form>
</div>
</body>
</html>
我的Server.js文件是:
var express= require('express');
var app= express();
app.use("/public", express.static(__dirname + "/public"))
app.all('/', function(req, res) {
res.sendFile('/express.js/public/signup.html');
});
app.post("/form", function(req, res){
var username= req.body.Name;
var email= req.body.Email;
var mobile= req.body.Mobile;
var password= req.body.Password;
var object= { name_new:username, mail: email, pass_word:password,
Mobile_No: mobile}
var json= JSON.stringify(obj);
});
app.listen(1111);
答案 0 :(得分:1)
您必须使用body-parser包解析您的请求
package.js
在路线上包含body-parser
npm install body-parser --save
现在,您将能够获取路线内的所有发布数据。
答案 1 :(得分:0)
您需要使用正文解析器才能在发布路线中使用req.body
:
var express= require('express');
var bodyParser = require('body-parser')
var app= express();
// parse forms with MIME type application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
app.use("/public", express.static(__dirname + "/public"))
app.all('/', function(req, res) {
res.sendFile('/express.js/public/signup.html');
});
app.post("/form", function(req, res){
var username= req.body.Name;
var email= req.body.Email;
var mobile= req.body.Mobile;
var password= req.body.Password;
var object= { name_new:username, mail: email, pass_word:password,
Mobile_No: mobile}
var json= JSON.stringify(obj);
});
app.listen(1111);
来自documentation of body-parser:
bodyParser.urlencoded([options])
返回仅解析urlencoded主体并且仅查看
Content-Type
标头与type
选项匹配的请求的中间件。该解析器仅接受主体的UTF-8编码,并支持gzip和deflate编码的自动填充。在中间件(即
req.body
)之后,在请求对象上填充了包含已解析数据的新主体对象。该对象将包含键值对,其中值可以是字符串或数组(扩展名为false
时)或任何类型(扩展名为true
时)。
答案 2 :(得分:0)
请查看expressjs的手册。您需要一个人体分析中间件
需求主体 包含在请求正文中提交的键/值数据对。默认情况下,它是未定义的,并且在使用诸如body-parser和multer之类的用于解析正文的中间件时填充。