$('.btn').on('click', function () {
$.ajax({
url: 'http://localhost:3000/reginst',
method: 'POST',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success ( *result* ) {
const data = JSON.parse( result )
switch ( data.status ) {
case 0:
$('small').html( data.info )
break;
case 1:
$('small').html( data.info )
break;
case 2:
setTimeout(() => {
localStorage.setItem('username',$('#username').val())
window.location.href = './login.html'
}, 1000);
break;
default:
break;
}
}
})
})
const express = require('express')
const db = require('../db')
const router = express.Router()
.post(async (*req*, *res*, *next*) => {
const result = await db.user.add( req.body )
res.render('reginst', {
data: JSON.stringify({
info: result.info,
status: result.status
})
})
})
module.exports = router
const mongoose = require( 'mongoose' )
*// 创建骨架模块*
*// const userSchema = new mongoose.Schema( options )*
*/**
*这里的options表示一个对象,对象中存储的就是字段和字段类型*
**/*
const userSchema = new mongoose.Schema({
username: String,
password: String
})
// 导出模块
module.exports = userSchema
const userModel = mongoose.model('users', userSchema)
const db = {
user: {
add(data) {} //向数据库增加数据
query(data){} //查询数据库数据
del(data){} //删除数据库数据
modify(data){} // 更改数据库数据
}
const mongoose = require( 'mongoose' )
const DBNAME = 'lilili' //创建数据库名称
*// mongoose.connect( 数据库地址,错误优先的回调函数)*
*// 数据库地址构成; mongodb://127.0.0.1:27017/数据库名称*
*// 错误优先的回调函数表示的事回调函数第一个参数是error*
const connect = {
init () {
mongoose.connect(`mongodb://127.0.0.1:27017/${ DBNAME }`, *error* => {
if ( error ) {
console.log( error )
} else {
console.log( `The db is connect success~~` )
}
})
}
}
module.exports = connect
const mongoose = require('mongoose')
const connect = require('./connect')
// 1. 链接数据库*
connect.init()
*// 2. 创建骨架 Schmea 定义字段*
const {
userSchema
} = require('./schema')
*// 3. 创建模型 Model*
*// const userModel = mongoose.model( 集合名称【复数】,对应的骨架 )*
const userModel = mongoose.model('users', userSchema) *// 很多人将集合名字没有写成复数*
const db = {
user: {
add(data) {} //向数据库增加数据
query(data){} //查询数据库数据
del(data){} //删除数据库数据
modify(data){} // 更改数据库数据
}
导入:
var reginstRouter = require('./routes/reginst');
var loginRouter = require('./routes/login');
var uppasswordRouter = require('./routes/uppassword');
var removeRouter = require('./routes/remove');
使用接口:
app.use('/',reginstRouter);
app.use('/',loginRouter);
app.use('/',uppasswordRouter);
app.use('/',removeRouter)
reginst.ejs文件:
<%- data %>
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 200
}))
接口:
app.use('/',reginstRouter);
app.use('/',loginRouter);
app.use('/',uppasswordRouter);
app.use('/',removeRouter)
注:cors是第三方模块,需要安装(npm install cors -S)