Mongodb连接数据库
//本地下载mongodb数据库(基本不用配置),安装express ,mongoose包
const express = require("express")
const app = express()
const bodyparser = require('body-parser');
//var jsonParser = bodyparser.json(); //json数据类型
const { User } = require("./models")
app.use(bodyparser.urlencoded({ extended: false })); //接收 x-www-form-urlencoded 参数
models.js
const mongoose = require("mongoose")
mongoose.connect("mongodb://localhost:27017/express-auth") //express-auth项目文件名 默认端口27017
const UserSchema = new mongoose.Schema({
email: { type: String, unique: true }, //字段唯一
name: { type: String },
password: {
type: String,
set(val) {
return require('bcrypt').hashSync(val, 10); //密码加密
}
},
indetity: { type: String }
})
const User = mongoose.model('User', UserSchema)
// User.db.dropCollection('users')
module.exports = { User }
//apifox接口工具
//获得user表
app.get('/users', async (req, res) => {
const users = await User.find()
res.send({ users })
})
//注册表
app.post('/api/register', async (req, res) => {
const user = await User.create({
email: req.body.email,
name: req.body.name,
password: req.body.password,
indetity: req.body.indetity
})
res.send(user)
})
接口工具踩坑 apifox
在传参的时候 req.body里数据一直为空 后发现传的格式有问题 需引入body-parser模块 在传 x-www-form-urlencoded 参数时需要 并全局引入
app.use(bodyparser.urlencoded({ extended: false }));
//传入json参数时
var jsonParser = bodyparser.json();
app.get('/users',jsonParser,async (req, res) =>{····}