安装中间件
npm i cors@2.8.5
使用中间件
const express = require('express');
const app = express();//创建一个以express应用,app实际上是一个函数,用于处理请求的函数
const path = require('path');
const rootPath = path.resolve(__dirname, '../public');
const cookieParser = require('cookie-parser');
const cors = require('cors')
const whiteApi = ['http://localhost:3333'];
// 设置cookieParser中间件
app.use(cors({
origin(origin, callback) {
console.log('origin', origin)
if (whiteApi.includes(origin)) {
callback(null, origin);
} else {
callback(new Error("not allowed"));
}
},
credentials: true,
exposedHeaders: 'token' // header中额外处理的其它属性
}))
// 使用跨域中间件
// 设置以后,会自动在req里面添加cookies属性,用于获取所有带来过来的cookies
// 设置以后,会在res对象中注入cookie方法,用于设置cookie
// app.use(cookieParser('1111')) // 使用111对cookie加密
app.use(cookieParser());
app.use(require('./middlewares/tokenHandleware'))
// 设置跨域请求
// app.use(require('./middlewares/coresHandleware'))
/***
* 发送请求的时,会根据请求的路径,从指定的目录中查找是否存在该文件,如果存在,则相应文件内容,而不再移交给后续的中间件,
* 如果不存在文件,则直接移交给后续的中间件
*/
app.use(express.static(rootPath, {
index: 'index.html' //默认访问页面,默认值为index.html,可修改
}));
// app.use('/static', express.static(rootPath))// 也可以针对访问某个指定api路径,来标识需要 返回静态资源
/***
* 默认res无法解析post请求的参数,也就是请求体
* 使用该中间件后表示,当Content-Type是"application/x-www-form-urlencoded",使用该中间件处理
*/
app.use(express.urlencoded({
extended: true
}))
/***
* 默认res无法解析post请求的参数,也就是请求体
* 使用该中间件后表示,当Content-Type是"application/json",使用该中间件处理
*/
app.use(express.json())
app.use('/api/admin', require('./api/admin'))
// 除了api请求
app.use('/api/student', require('./api/student'))
app.use(require('./middlewares/errMiddleware')) // 处理所有的错误请求
app.listen(12306, () => {
console.log('server on 12306 has started')
})
- whiteapi是自定义的一个白名单,如果请求在白名单内部则允许跨域
- 如果不在,就直接报错
credentials: true
允许携带cookie凭证