安装中间件

npm i cors@2.8.5

官网:https://github.com/expressjs/cors#readme

使用中间件

  1. const express = require('express');
  2. const app = express();//创建一个以express应用,app实际上是一个函数,用于处理请求的函数
  3. const path = require('path');
  4. const rootPath = path.resolve(__dirname, '../public');
  5. const cookieParser = require('cookie-parser');
  6. const cors = require('cors')
  7. const whiteApi = ['http://localhost:3333'];
  8. // 设置cookieParser中间件
  9. app.use(cors({
  10. origin(origin, callback) {
  11. console.log('origin', origin)
  12. if (whiteApi.includes(origin)) {
  13. callback(null, origin);
  14. } else {
  15. callback(new Error("not allowed"));
  16. }
  17. },
  18. credentials: true,
  19. exposedHeaders: 'token' // header中额外处理的其它属性
  20. }))
  21. // 使用跨域中间件
  22. // 设置以后,会自动在req里面添加cookies属性,用于获取所有带来过来的cookies
  23. // 设置以后,会在res对象中注入cookie方法,用于设置cookie
  24. // app.use(cookieParser('1111')) // 使用111cookie加密
  25. app.use(cookieParser());
  26. app.use(require('./middlewares/tokenHandleware'))
  27. // 设置跨域请求
  28. // app.use(require('./middlewares/coresHandleware'))
  29. /***
  30. * 发送请求的时,会根据请求的路径,从指定的目录中查找是否存在该文件,如果存在,则相应文件内容,而不再移交给后续的中间件,
  31. * 如果不存在文件,则直接移交给后续的中间件
  32. */
  33. app.use(express.static(rootPath, {
  34. index: 'index.html' //默认访问页面,默认值为index.html,可修改
  35. }));
  36. // app.use('/static', express.static(rootPath))// 也可以针对访问某个指定api路径,来标识需要 返回静态资源
  37. /***
  38. * 默认res无法解析post请求的参数,也就是请求体
  39. * 使用该中间件后表示,当Content-Type"application/x-www-form-urlencoded",使用该中间件处理
  40. */
  41. app.use(express.urlencoded({
  42. extended: true
  43. }))
  44. /***
  45. * 默认res无法解析post请求的参数,也就是请求体
  46. * 使用该中间件后表示,当Content-Type"application/json",使用该中间件处理
  47. */
  48. app.use(express.json())
  49. app.use('/api/admin', require('./api/admin'))
  50. // 除了api请求
  51. app.use('/api/student', require('./api/student'))
  52. app.use(require('./middlewares/errMiddleware')) // 处理所有的错误请求
  53. app.listen(12306, () => {
  54. console.log('server on 12306 has started')
  55. })
  1. whiteapi是自定义的一个白名单,如果请求在白名单内部则允许跨域
  2. 如果不在,就直接报错
  3. credentials: true允许携带cookie凭证