首先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