vue-element-admin 前后端交互(解决跨域)

一、移除MOCK,前后端交互

1.修改 vue.config.js

  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // before: require('./mock/mock-server.js'),// 替换mock需要注释当前代码
    /**
     * @see https://www.cnblogs.com/haoxianrui/p/13624548.html
     */
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://tp.local',// 当前地址为接口地址
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    }
  },

2.注释代码 src/main.js 

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
// 替换mock需要注释当前代码
// if (process.env.NODE_ENV === 'production') {
//   const { mockXHR } = require('../mock')
//   mockXHR()
// }

3.修改对应环境的api 地址

a. .env.development 

VUE_APP_BASE_API = '/api'  // 修改为项目对应的地址

b. .env.production

VUE_APP_BASE_API = '/api'  // 修改为项目对应的地址

c. .env.staging 

VUE_APP_BASE_API = '/api'  // 修改为项目对应的地址

4.修改对应的请求地址---例如登录接口( src/api/user.js )

// 登录接口
export function login(data) {
  return request({
    url: '/user/login', // 控制器/方法
    method: 'post',
    data
  })
}

// 获取用户基本配置信息(权限信息)
export function getInfo() {
  return request({
    url: '/user/config', // 控制器/方法
    method: 'post'
  })
}

// 退出登录
export function logout() {
  return request({
    url: '/user/logout', // 控制器/方法
    method: 'post'
  })
}

5.修改axios请求方法

修改 src/utils/request/js

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  transformRequest: function(data) { // 格式化请求数据
    let ret = ''
    for (var it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  },
  timeout: 20000 // request timeout
})


service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = getToken() // 获取token缓存,
    const tokenType = getTokenType() // 获取token缓存类型,此为作者自己封装的方法
    if (token && tokenType) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      console.log('add token')
      config.headers['X-Token'] = token 
      config.headers['Authorization'] = tokenType + ' ' + token // TODO JWT验证用户是否已经登录的验证方式
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

5.服务器配置

本地环境 

# 本地环境
server {
        listen 80;
        server_name admin.local;
        index index.html index.htm index.php;
        location / {
                proxy_buffers 8 32k;
                proxy_buffer_size 64k;

                # websocket
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";

                client_max_body_size 500m;
                proxy_pass http://127.0.0.1:3864/;#此处修改为本地环境地址
        }
        location /api {
                rewrite  ^.+api/?(.*)$ /$1 break;
                include  uwsgi_params;
                proxy_pass   http://api.admin.local; #此处修改为项目接口地址
        }
}

线上环境

# 线上环境
server{
    listen 80;
    server_name admin.server;
    index index.html index.htm index.php default.html default.htm default.php;
    root /data/admin/dist; # 生成缓存文件的项目地址

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
    }
    location /api {
        rewrite  ^.+api/?(.*)$ /$1 break;
                include  uwsgi_params;
                proxy_pass   http://api.admin; #此处修改为项目接口地址
        }
        location ~ .*\.(js|css)?$ {
        expires      12h;
    }
    location /admin{
        try_files $uri $uri/ /index.html;
    }

    location ~ /\. {
        deny all;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值