Eggjs 设置跨域请求 指定地址跨域 nodejs

首先egg自身框架没有直接设置允许跨域请求的功能和接口,所以需要第三方包来设置跨域请求!

  • 先安装第三方包来设置跨域,使用egg-cors
// npm
npm i egg-cors --save
// cnpm 
cnpm i egg-cors --save
// yarn 
yarn add  egg-cors 
  • 设置egg框架plugin.js文件 目录 ${root}/config/plugin.js
module.exports = {
  ...
  //跨域插件  
  cors: {
    enable: true,
    package: 'egg-cors',
  },
};
  • 设置egg框架config.default.js 目录${root}/config/config.default.js
...

config.security = {
    csrf: {
      enable: false,
    },
    domainWhiteList: [ '*' ],
  };
  config.cors = {
    origin: ctx => ctx.get('origin'), //这种方式是允许所有的IP+端口跨域访问
    credentials: true, // 开启认证
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', //允许请求的方式
};
  •  若想指定某个地址允许跨域访问则需要单独设置origin即可
 origin: 'http://localhost:3001'

这样你本地的Vue,React 项目就可以请求Egg框架的api了。

import axios from "axios";
const BASEURL = process.env.NODE_ENV === "development" ? "http://127.0.0.1:7001/" : "http://127.0.0.1:7001/" //后端地址
const config = {


    // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
    // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
    baseURL: BASEURL,


    // `headers` 是即将被发送的自定义请求头
    headers: { 'X-Requested-With': 'XMLHttpRequest' },


    // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
    // 如果请求话费了超过 `timeout` 的时间,请求将被中断
    timeout: 60 * 1000,

    // `withCredentials` 表示跨域请求时是否需要使用凭证
    withCredentials: true, // default
}

const myAjax = axios.create(config)
export default myAjax