文章目录
初始化路由模板
- 1.在 router 文件夹中,新建 user.js 文件,作为用户的路由模块,并初始化代码如下:
const express = require('express') // 创建路由对象 const router = express.Router() // 注册新用户 router.post('/reguser', (req, res) => { res.send('reguser OK') }) // 登录 router.post('/login', (req, res) => { res.send('login OK') }) // 将路由对象共享出去 module.exports = router
- 2.在 app.js 中,导入并使用 用户路由模块 :
/ 导入并注册用户路由模块 const userRouter = require('./router/user') app.use('/api', userRouter)
- 3.在 /router_handler/user.js 中,使用 exports 对象,分别向外共享如下两个 路由处理函
数 :
** * 在这里定义和用户相关的路由处理函数,供 /router/user.js 模块进行调用 */ // 注册用户的处理函数 exports.regUser = (req, res) => { res.send('reguser OK') } // 登录的处理函数 exports.login = (req, res) => { res.send('login OK') }
- 4.将 /router/user.js 中的代码修改为如下结构:
const express = require('express') const router = express.Router() // 导入用户路由处理函数模块 const userHandler = require('../router_handler/user') // 注册新用户 router.post('/reguser', userHandler.regUser) // 登录 router.post('/login', userHandler.login) module.exports = router
数据库和前端页面交互
编写注册的后台接口
先连接数据库
//插入新用户 const mongoose = require('mongoose'); //连接mongodb服务 mongoose.connect('mongodb://127.0.0.1:27017/login'); mongoose.connection.once('open', () => { let LoginSchema = new mongoose.Schema({ name: { type: String, }, password: String }); let LoginModel = mongoose.model('persons', LoginSchema); LoginModel.create({ name: userinfo.name, password: userinfo.password }, (err, data) => { if (err) { console.log(err); res.send({ status: 1, message: '注册失败,用户名已存在!' }) } res.send({ status: 0, message: '成功注册!欢迎:'+PeapleName }) mongoose.disconnect(); }) }); }
和前台进行数据交互
xhr.open('POST', 'http://127.0.0.1:3007/api/reguser') xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send('name=' + ResVal + '&password=' + ResVal1) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.response) if (response.status == 0) { alert(response["message"]); window.location.href = "login" } else { alert(response["message"]); } } } }
文章的后台接口
先查询所有的文章内容
exports.findAllarticle = (req,res)=>{ //1.引入mongoose const mongoose = require('mongoose'); //2.链接mongodb数据库 connect 连接 mongoose.connect('mongodb://127.0.0.1:27017/article'); //4.声明文档结构 const ArticleSchema = new mongoose.Schema({ content:String, title:String }) //6.创建模型对象 const ArticleModel = mongoose.model('aiticle', ArticleSchema); ArticleModel.find(function (err, data) { if(err) { res.send({ status:1, msg:'查询失败!' }) }else{ res.send({ status:0, data:data, msg:'查询成功' }) } } ) }
//查询数据库渲染页面 const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://127.0.0.1:3007/find/findall') xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send() xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.response) if (response.status == 0) { const data = response['data'] for (let i = 0; i < data.length; i++) { res = data[i] var li = document.createElement('li') content.appendChild(li) li.innerHTML = `<a href='#'>` + `<h1>` + res["title"] + `</h1>` + `<br>` + res["content"] + `</a>` + `<br>` + "来自id为:" + str + "发布的文章" + ` ` + "时间是:" + nowTime var contents = document.querySelectorAll('.content ul li') for (let i = 0; i < contents.length; i++) { contents[i].addEventListener('click', function () { var about = res["_id"] window.location.href = "content?" + encodeURIComponent(about) }) } } } else { alert(response["msg"]); } } } }
发文章
// 发布新文章的处理函数 exports.addArticle = (req, res) => { const article = req.body //1.引入mongoose const mongoose = require('mongoose'); //2.链接mongodb数据库 connect 连接 mongoose.connect('mongodb://127.0.0.1:27017/article'); //4.声明文档结构 const ArticleSchema = new mongoose.Schema({ content: String, title:String, author:String }) //6.创建模型对象 const ArticleModel = mongoose.model('aiticle', ArticleSchema); ArticleModel.create({ content: article.content, title:article.title, author:article.author }, function (err, data) { if(err) { res.send({ status:1, msg:'发布失败!' }) }else{ res.send({ status:0, data:data.content, title:data.title, id:data.id, msg:'发布成功!' }) } console.log(err); return } ) }
const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://127.0.0.1:3007/my/article/add') xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send('content=' + fabuText.value + '&title=' + title.value+'&author='+str) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.response) if (response.status == 0) { var li = document.createElement('li') content.appendChild(li) li.innerHTML = `<a href='#'>` + `<h1>` + response["title"] + `</h1>` + `<br>` + response["data"] + `</a>` + `<br>` + "来自用户为:" + str + "发布的文章" + ` ` + "时间是:" + nowTime fabuText.value = null title.value = null alert(response["msg"]) var contents = document.querySelectorAll('.content ul li') for (let i = 0; i < contents.length; i++) { contents[i].addEventListener('click', function () { var about = response["id"] window.location.href = "content?" + encodeURIComponent(about) }) } } else { alert(response["msg"]); } } } }
一些验证方法
邮箱验证
function isEmail(str){ var reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; return reg.test(str) }
用户名随机生成
//1.先定义时间函数 function timestampToTime(times) { let time = times[1] let mdy = times[0] mdy = mdy.split('/') let month = parseInt(mdy[0]); let day = parseInt(mdy[1]); let year = parseInt(mdy[2]) return year + '-' + month + '-' + day + ' ' + time } let time = new Date() let nowTime = timestampToTime(time.toLocaleString('en-US', { hour12: false }).split(" ")) //2.随机字符串函数 var zifu=Math.random().toString(36).substring(2); var PeapleName=nowTime+'-'+zifu