全部代码:
html代码:
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>viewOne</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="../public/style.css" />
</head>
<body>
<div class="content">
<header class="common-header">
<a class="icon-back" href="javascript:history.go(-1);"></a>
<span>viewTwo取消</span>
</header>
<div>
<form action="http://192.168.10.57:4000/regist" method="get">
<input type="text" name="first_name" />
<br>
<input type="text" name="last_name"/>
<input type="submit" value="提交">
</form>
</div>
</div>
</body>
<script type="text/javascript">
var adaptPageClass = 'content';
</script>
</html>
后台代码:
var MongoClient = require('mongoose');
MongoClient.connect('mongodb://localhost:27017/node数据库',{ useNewUrlParser: true },function () { //27017是数据库端口,node数据库是数据库名
console.log('test')
});
//提示数据库是否链接成功
var db = MongoClient.connection;
db.on('open',function () {
console.log('MongoDB链接成功')
})
db.on('error',function () {
console.log('MongoDB连接失败');
})
var Schema = MongoClient.Schema; //创建一个Schema模型骨架,并且设置好user模版
var userSchema = new Schema({
firstName:{type:String},
lastName:{type:String}
});
var User = MongoClient.model("User",userSchema); //Schema发布一个User的Model
app.get('/regist',function (req,res) { 处理regist的get请求
console.log('轻取i成功')
console.log(req.query.first_name)
var user_1 = new User({
firstName: req.query.first_name,
lastName: req.query.last_name
});
user_1.save(function () {
res.send('数据插入成功'); //插入数据并且提示数据库插入成功
});
});
1、链接数据库:
var MongoClient = require('mongoose');
MongoClient.connect('mongodb://localhost:27017/node数据库',{ useNewUrlParser: true },function () { //27017是数据库端口,node数据库是数据库名
console.log('test')
});
//提示数据库是否链接成功
var db = MongoClient.connection;
db.on('open',function () {
console.log('MongoDB链接成功')
})
db.on('error',function () {
console.log('MongoDB连接失败');
})
2、创建一个Schema骨架模型,并且设计好user模板
var Schema = MongoClient.Schema; //创建一个Schema模型骨架,并且设置好user模版
var userSchema = new Schema({
firstName:{type:String},
lastName:{type:String}
});
3、发布模型
var User = MongoClient.model("User",userSchema); //Schema发布一个User的Model
4、处理前端请求
app.get('/regist',function (req,res) { 处理regist的get请求
console.log('轻取i成功')
console.log(req.query.first_name)
var user_1 = new User({
firstName: req.query.first_name,
lastName: req.query.last_name
});
user_1.save(function () {
res.send('数据插入成功'); //插入数据并且提示数据库插入成功
});
});
借鉴自:https://blog.csdn.net/qwe502763576/article/details/79646551
http://vince.xin/article/5acc33286b78214ab8ac58b6