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
| const http = require('http') const app = http.createServer() const fs = require('fs') const url = require('url') const path = require('path') const { json } = require('express') let lodash = require('lodash') app.on('request', (req, res) => { req.url = req.url.toLowerCase() let urlObj = url.parse(req.url, true) if (req.url == '/' || req.url == 'index' || req.url == 'submit') { fs.readFile(path.join(__dirname, 'view', 'submit.html'), 'utf8', (err, data) => { if (err) throw err res.end(data) }) } else if (req.url == '/login') { fs.readFile(path.join(__dirname, 'view', 'login.html'), 'utf8', (err, data) => { if (err) throw err res.end(data) }) } else if(req.url == "/home"){ fs.readFile(path.join(__dirname, 'view', 'home.html'), 'utf8', (err, data) => { if (err) throw err res.end(data) }) } else if (req.url.startsWith('/add') && req.method == 'GET') { let content = urlObj.query fs.readFile(path.join(__dirname, 'data', 'kaoshi.json'), 'utf8', (err, data) => { if (err && err.code != 'ENOENT') throw err let arr = JSON.parse(data || '[]') arr.push(content) fs.writeFile(path.join(__dirname,'data','kaoshi.json'),JSON.stringify(arr,null,' '),(err)=>{ if(err) throw err res.writeHead(302, 'Found', { 'Location': 'login' }) res.end() })
}) } else if(req.url.startsWith('/out')&& req.method=='GET'){ let count = urlObj.query fs.readFile(path.join(__dirname,'data','kaoshi.json'),'utf-8',(err,data)=>{ if(err) throw err let arr = JSON.parse(data) var m = lodash.findIndex(arr, count) if(m>=0){ res.writeHead(302, 'Found', { 'Location': '/home' }) res.end() } })
} }).listen(3000, () => { console.log("服务启动,请访问:http://localhost:3000") })
|