全部代碼:
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; //創(chuàng)建一個Schema模型骨架,并且設置好user模版
var userSchema = new Schema({
firstName:{type:String},
lastName:{type:String}
});
var User = MongoClient.model("User",userSchema); //Schema發(fā)布一個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、創(chuàng)建一個Schema骨架模型婚温,并且設計好user模板
var Schema = MongoClient.Schema; //創(chuàng)建一個Schema模型骨架描焰,并且設置好user模版
var userSchema = new Schema({
firstName:{type:String},
lastName:{type:String}
});
3、發(fā)布模型
var User = MongoClient.model("User",userSchema); //Schema發(fā)布一個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