-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathapp.js
47 lines (35 loc) · 1.17 KB
/
app.js
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
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const path = require('path')
const koaStatic = require('koa-static')
const router = require('./src/routers/index')
const app = new Koa()
// 跨域中间件
app.use(cors({
origin: ctx => {
const localhost = new RegExp(/^(localhost)/)
if (localhost.test(ctx.request.header.host)) {
return '*'
}
//如果你想要拦截跨域可以返回false
// return false
return '*'
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
// 配置静态资源中间件
app.use(koaStatic(
path.join(__dirname, 'dist')
))
app.use(bodyParser()) //post解析中间件
app.use(router.routes()); //作用:启动路由
app.use(router.allowedMethods());
/* 作用: 这是官方文档的推荐用法,我们可以看到router.allowedMethods()用在了路由匹配
router.routes()之后,目的在于:根据ctx.status 设置response 响应头
*/
app.listen(3000)