var express = require('express'); var router = express.Router(); var bodyParser=require('body-parser'); var app=express(); var Info=require('../models/info'); var tokens=require('../config/token.js'); app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); var expressJWT=require('express-jwt'); router.get('/test', function(req, res, next) { res.json({ msg:'info api' }) }) router.post('/add', function(req, res, next) { const inf={} console.log(req.user) if(!req.user.name){ return res.json({ status:1, msg:'token失效' }) }else{ if(req.body.name) inf.name=req.body.name if(req.body.zhiwei) inf.zhiwei=req.body.zhiwei if(req.body.company) inf.company=req.body.company if(req.body.depar) inf.depar=req.body.depar var infoAdd=new Info(inf); infoAdd.save().then(doc=>{ res.json({ status:0, result:inf }) }) } }) //获取所有信息 router.get('/', function(req, res, next) { if(!req.user.name){ res.json({ status:1, msg:'token失效,或者未登录' }) }else{ Info.find().then(info=>{ res.json({ status:0, result:info }) }) } }) //获取单个信息 router.get('/:id', function(req, res, next) { if(!req.user.name){ res.json({ status:1, msg:'token失效,或者未登录' }) }else{ console.log(req.params.id) Info.findOne({ _id:req.params.id }).then(info=>{ res.json({ status:0, result:info }) }).catch(err=>{ res.status(404).json({ status:1, msg:err }) }) } }) //编辑信息 router.post('/edit', function(req, res, next) { let inf={} if(!req.user.name){ return res.json({ status:1, msg:'token失效' }) }else{ let _id=req.body.id; if(req.body.name) inf.name=req.body.name if(req.body.zhiwei) inf.zhiwei=req.body.zhiwei if(req.body.company) inf.company=req.body.company if(req.body.depar) inf.depar=req.body.depar Info.findOneAndUpdate( {_id}, {$set:inf}, {new:true} ).then(info=>{ res.json({ status:0, result:info }) }).catch(err=>{ res.json({ status:1, msg:err }) }) } }) //删除信息 router.delete('/delete', function(req, res, next) { let inf={} if(!req.user.name){ return res.json({ status:1, msg:'token失效' }) }else{ // console.log(typeof req.body.id) let _id=req.body.id; if(typeof _id=='string'){ //删除一条 Info.findOneAndRemove({_id}).then(info=>{ res.json({ status:0, msg:'删除成功' }) }).catch(err=>{ res.json({ status:1, result:err }) }) }else{ //多条删除 Info.remove({ _id: { $in: _id} }).then(infos=>{ res.json({ status:0, msg:'删除成功' }) }).catch(errs=>{ res.json({ status:1, msg:'删除失败' }) }) } } }) module.exports = router;
参考文章:https://www.jianshu.com/p/2f54b90efe15
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接