推荐:https://juejin.cn/post/7032934725459279909

https://juejin.cn/post/6995063516470198279#heading-9

1.安装

初始化:
npm install egg --type=simple
安装依赖: npm intall

启动: npm run dev
默认地址是 http://localhost:7001

修改启动地址、端口:config -> config.default.js

  1. ...
  2. module.exports = appInfo => {
  3. /**
  4. * built-in config
  5. * @type {Egg.EggAppConfig}
  6. **/
  7. const config = exports = {};
  8. // code start
  9. config.cluster = {
  10. listen: {
  11. path: '',
  12. port: 8001, // 端口
  13. hostname: '127.0.0.1', // 0.0.0.0
  14. }
  15. }
  16. // code end
  17. return {
  18. ...config,
  19. };
  20. };
  21. ...

2.跨域

安装跨域插件
npm i egg-cors --save

配置config下的plugin.js

  1. 'use strict';
  2. /** @type Egg.EggPlugin */
  3. module.exports = {
  4. // had enabled by egg
  5. // static: {
  6. // enable: true,
  7. // }
  8. cors: {
  9. enable: true,
  10. package: 'egg-cors',
  11. },
  12. };

配置config下的config.default.js

  1. // 关闭crsf,开启跨域
  2. config.security = {
  3. csrf: {
  4. enable: false,
  5. },
  6. domainWhiteList: [ ],
  7. };
  8. // 允许跨域方法
  9. config.cors = {
  10. origin: '*',
  11. allowMethods: 'GET, PUT, POST, DELETE, PATCH',
  12. };