var express = require('express')
var cors = require("cors")
var session = require("express-session")
var bodyParser = require("body-parser");
var whitelist = require("./config/whitelist.json")
var userlist = require("./config/user.json")
var app = express();
console.log('userlist', userlist)
app.use(express.static('./public'))
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}));
app.use(session({
secret: +new Date()+"abc",
cookie: {maxAge: 10 * 1000}
}))
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
res.header("X-Powered-By", ' 3.2.1')
if (req.method == "OPTIONS") res.send(200);/*让options请求快速返回*/
else next();
});
app.get("", function (req, res) {
res.send("home")
})
app.get("/", function (req, res) {
console.log("It works! version: ", process.env.npm_package_version);
console.log("req-cookie", req.headers.cookie);
res.send("It works! version: " + process.env.npm_package_version);
});
// 登录接口
app.post("/login", function (req, res, next) {
let code, msg, data;
const {username, password} = req.body;
if (username && userlist[username] === password) {
req.session.username = username;
code = 0;
msg = "success";
data = "登录成功"
} else {
code = -1;
msg = "error";
data = "账号或者密码不正确"
}
res.send({code, msg, data})
})
app.get("/identity", function (req, res, next) {
let code = 0, msg = "", data = {anonymous:true,username:""};
console.log("req.session", req.session);
if (req.session && req.session.username) {
data.anonymous=false;
data.username=req.session.username;
} else {
data.anonymous = true;
}
res.send({data, code})
})
app.listen(3003);
console.log("localhost:3003")