使用express框架创建服务端
const express=require(`express`)const morgan=require(`morgan`)const serveFavicon=require(`serve-favicon`)const bodyParser=require(`body-parser`)const app=express() //返回一个应用对象给appconst ejs=require(`ejs`)const session=require(`express-session`)//设置端口号app.set(`port`,8090)//配置express-session,要放在最前面app.use(session({secret:`abcdefg`, //加密的session数据 name:`demo`, //返回给客户端cookie的name值,可以不写 cookie:{maxAge:1000*10}, //失效时间 rolling:false, //更新失效时间,上线时设为true resave:false , //重新保存,上线时设为true saveUninitialized:false //是否强制将“未初始化”的会话保存到存储中}))app.use(bodyParser.json())//定义数据格式为json格式app.use(bodyParser.urlencoded({extended:false}))app.use(morgan(‘dev‘))//配置ejsapp.set(`views`,__dirname+`/view`)//app.set(`view engine`,`ejs`)app.engine(`html`,ejs.__express)app.set(‘view engine‘,‘html‘)//app.use(serveFavicon(__dirname+`/`)),__dirname==my_node(根目录)app.use(express.static(__dirname+`/public`)) //配置静态资源app.use(express.static(__dirname+`/public/pages`))var sc=require(`./routes/scenic`)app.use(sc)//监听端口app.listen(app.get(`port`),function () {//引用路由模板 //一般要写在全局 console.log("服务器运行,端口号8090")//配置白名单解决跨域问题/* app.all(‘*‘, function(req, res, next) { console.log(req.method); res.header("Access-Control-Allow-Origin", "*"); res.header(‘Access-Control-Allow-Headers‘, ‘Content-type‘); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH"); res.header(‘Access-Control-Max-Age‘,1728000);//预请求缓存20天 next(); });*/ var loginRoute=require(`./routes/routeUser`)var searchRoute=require(`./routes/routePaient`)var email=require(`./routes/routeTools`)// 使用路由模板 //一般要写在全局 app.use(function (req, res, next) { //自定义中间件 console.log(‘req.url:‘,req.url); next(); //一定要写next(),数据才会传递给下一下中间件; }) app.use(loginRoute) app.use(searchRoute) app.use(email)//返回404页面 app.use(‘*‘,function (req,res,next) { //*表示根目录下的页面 //如果没有直接 res.status(404) res.sendFile(__dirname+`/public/404.html`)//next() app.use放在前面要加next()方法,数据才能传给下一个中间件 })})
相关推荐
webgm 2020-08-16
lei0 2020-11-02
igogo00 2020-07-04
iconhot 2020-06-26
88481456 2020-06-18
yezitoo 2020-06-06
SelinaChan 2020-05-15
luckymaoyy 2020-04-25
80437700 2020-04-17
austindev 2020-04-07
我有一只小松鼠 2020-02-29
webfullStack 2020-02-15
binglingnew 2012-10-03
始作俑者 2020-01-19
jinxiutong 2020-01-04
Dawnworld 2019-12-23
yezitoo 2019-12-05
moyigg 2019-12-02