1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| const jsonServer = require('json-server') const path = require('path') const server = jsonServer.create() const data = require('./data')
const router = jsonServer.router(data()) const middlewares = jsonServer.defaults()
function resData(data={}, code=200, msg='') { return { code, data, msg } }
router.render = (req, res) => { res.jsonp(resData(res.locals.data, res.statusCode)) }
server.use(middlewares)
server.use(jsonServer.bodyParser) server.use((req, res, next) => { next() })
let session
server.get('/api/user', (req, res) => { if (session) { res.jsonp(resData(session, 200)) } else { res.jsonp(resData(undefined, 403, '未登录')) } })
server.post('/api/login', (req, res) => { let body = req.body, code = 302, data = {}, msg = '密码错误' if (body.username === 'admin' && body.password === 'admin') { msg = '' code = 200 data = req.body data.id = 1 delete data.password session = data } res.jsonp(resData(data, code, msg)) })
server.get('/api/logout', (req, res) => { session = null res.jsonp(resData({}, 200, '注销成功')) })
server.use('/api', router) const port = 9999 server.listen(port, () => { console.log('JSON Server is running, port: '+ port) })
|