想学习更多,请关注个人微信GZH:Magic全靠想象
0. 大致步骤
1. 开发环境跨域解决
1)、创建并配置vue.config.js
module.exports = {
devServer: {
// 代理跨域的配置
proxy: {
// 当我们的本地的请求 有/api的时候,就会代理我们的请求地址向另外一个服务器发出请求
// 这里的api 表示如果我们的请求地址有/api的时候,就触发代理机制
// localhost:8888/api/abc => 代理给另一个服务器
'/api': {
target: 'http://localhost:8080', // 跨域请求的地址
changeOrigin: true, // 只有这个值为true的情况下 才表示开启跨域
// secure: false, // 如果是https接口,需要配置这个参数
// 路径重写
pathRewrite: {
// 重新路由 localhost:8888/api/login => www.baidu.com/api/login
'^/api': '' // 假设我们想把 localhost:8888/api/login 变成www.baidu.com/login 就需要这么做
}
}
}
}
}
// 注意:修改了配置文件后一定要重启才会生效
2)、在封装的axios中配置baseUrl
import axios from 'axios'
// 当前环境
let isPro = process.env.NODE_ENV === 'production';
const axios1 = axios.create({
// '/api' 只有在开发环境下才会生效。在生产环境下需要通过Nginx监听api请求转发才行
baseURL: '/api',
timeout:100000,
method:'post',
headers:{
'Content-Type':'application/json;charset=UTF-8',
'token':localStorage.getItem("token")
}
})
export function req1(config){
return axios1({
....
})
}
export function req2(config){
return axios1({
......
})
}
2. 生产环境下的跨域问题
在生产环境下主要通过配置Nginx的代理来进行转发
主要是通过配置location的拦截路径来拦截 /api请求来转发到真正的服务器地址
location /api { # 重写/api rewrite ^/api/(.*)$ /$1 break; # 服务器地址 proxy_pass http://www.xxxx.xxxx:8080; }
server {
listen 8080;
server_name localhost;
location / {
#root html;
root F:\HbuilderProject\vue-cli\cli14-component-page\dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
# 重写/api
rewrite ^/api/(.*)$ /$1 break;
# 服务器地址
proxy_pass http://www.xxxx.xxxx:8080;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}