剛學(xué)了 express 和 mongoDB,結(jié)合 vue,想著搭建一個全棧的小 demo,然后就用簡單的表單提交體驗了一下。現(xiàn)在前后端分離溉仑,兩者完全可以分開做,然后通過相關(guān)的接口實現(xiàn)數(shù)據(jù)的交互肆氓。具體看圖:
image.png
簡單來說去枷,就是:前端通過 axios 跨域獲取后端的接口中數(shù)據(jù),進(jìn)行相關(guān)的渲染邪码;后端則將前端 post 過來的處理后保存到數(shù)據(jù)庫中裕菠。
demo 功能
將表單中的數(shù)據(jù)保存到數(shù)據(jù)庫。
技術(shù)棧
前端
vue + axios
后端
express + mongoDB
具體實現(xiàn)
準(zhǔn)備
- webpack 構(gòu)建項目
- npm 安裝 axios 闭专、express 奴潘、 body-parser 、mongoose影钉。
前端
- 編寫表單樣式
image.png
- 通過 axios 跨域獲取后端接口中的數(shù)據(jù)画髓,實現(xiàn)數(shù)據(jù)寫和讀。
<script>
export default {
name: 'App',
data(){
return {
name: '',
password: ''
}
},
methods: {
add(){
this.axios.get('/api/register/get')
.then((res) => {
// console.log(res);
let param = {
name: this.name,
password: this.password
};
this.axios.post('/api/register/add', param);
}).catch(err => {
console.log('error...');
})
}
}
}
</script>
后端
- 在項目根目錄下新建一個文件夾 server平委, 用于保存接口的 js 文件奈虾。
image.png
- db.js
主要實現(xiàn)數(shù)據(jù)庫模塊。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/exdb');
// 數(shù)據(jù)庫連接狀態(tài)判斷
let db = mongoose.connection;
db.once('error', (req, res) => {
console.log('Mongodb connect error...');
});
db.once('open', (req, res) => {
console.log('Mongodb connect succeed...');
});
let worker = mongoose.Schema({
name: {
type: String,
default: '某人'
},
password: {
type: Number,
default: 18
}
});
module.exports = mongoose.model('worker', worker);
- api.js
主要實現(xiàn)數(shù)據(jù)庫中數(shù)據(jù)的讀取。
const express = require('express');
const app = express();
// body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// 引進(jìn)數(shù)據(jù)庫模塊
const worker = require('./db.js');
app.post('/api/register/add', (req, res) => {
worker.findOne({'name': req.body.name}, 'name', (err, result) => {
if(err){
res.send('mongoose find error...');
}else{
if(!result){
// 添加到數(shù)據(jù)庫
new worker({
name: req.body.name,
password: req.body.password
}).save();
}
}
});
});
app.get('/api/register/get', (req, res) => {
worker.find((err, result) => {
if(err){
res.send('mongoose find error...');
}else{
res.send(result);
}
});
});
// '/'
// app.get('/', (req, res) => {
// res.type('text/plain');
// res.send('main...');
// });
// 404
app.use((req, res, next) => {
res.status(404);
res.type('text/plain');
res.send('404 - not found.');
next();
});
// 500
app.use((req, res, next) => {
res.status(500);
res.type('text/plain');
res.send('500 - server error.');
next();
});
app.listen(8081, (req, res) => {
console.log('The Port 8081 is running, press the Ctrl + C to stop...')
});
設(shè)置代理
前端的默認(rèn)端口號是:8080肉微, 而我的后端設(shè)置的端口號設(shè)置為:8081匾鸥,這時候,就需要去設(shè)置代理碉纳,實現(xiàn)端口的代理勿负。具體如下:在文件夾 config 中找到 index.js 文件,并在文件中添加以下代理代碼:
proxyTable: {
"/api": {
target: "http://localhost:8081/api/",
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
}
}
通過設(shè)置代理劳曹,就將端口8080和端口8081統(tǒng)一起來奴愉,然后前端的數(shù)據(jù)就可以傳送到后端,交由后端處理厚者。
最后效果
前端填寫數(shù)據(jù)
image.png
后端獲取數(shù)據(jù)
image.png
數(shù)據(jù)庫
image.png