axios跨域代理设置baseURL的一些问题
1、为什么会跨域先了解跨域的概念:发送请求的url的协议、域名、端口三者之间任意一个与当前页面的地址不同则视为跨域。axios解决跨域很简单,只需要在vue.config.js 设置 proxy 就可以了。vue.config.jsdevServer: {port: 8888,proxy: {'/dev-server':{target: 'http://localhost:8886/',...
1、为什么会跨域
先了解跨域的概念:发送请求的url的协议、域名、端口三者之间任意一个与当前页面的地址不同则视为跨域。
axios解决跨域很简单,只需要在 vue.config.js 设置 proxy 就可以了。
vue.config.js
devServer: {
port: 8888,
proxy: {
'/dev-server':{
target: 'http://localhost:8886/',
// 跨域配置
changeOrigin: true,
// 路径重写
pathRewrite:{
'^/api': '/'
}
},
'/prod-server':{
target: 'http://localhost:8887/',
// 跨域配置
changeOrigin: true,
// 路径重写
pathRewrite:{
'^/api': '/'
}
}
}
}
封装axios请求。
import axios from 'axios'
const baseUrl = "dev-server"
class HttpRequest {
constructor(baseUrl){
this.baseUrl = baseUrl
}
getDefaultConfig(){
const config = {
baseURL: this.baseUrl
}
return config
}
request(options){
const instance = axios.create()
options = Object.assign(this.getDefaultConfig(), options)
return instance(options)
}
}
export default new HttpRequest(baseUrl)
处理跨域问题很简单,只需要设置baseURL,将端口进行代理于同一端口下,即使前后端分离,只要前端能直接访问到target的地址就问题不大。
2、开发环境生产环境自动配置
在Vue项目的根目录下分别建立两个文件
.env.development 和 .env.production ,其中的 ' . ' 字符不可忽略。
#开发
.env.development
VUE_APP_BASEURL=/dev-server
#生产
.env.production
VUE_APP_BASEURL=/prod-server
development 开发环境,和上面 vue.config.js 配置的 dev-server 相对,在开发时 axios 获取 server 的 baseURL 就会匹配 http://localhost:8886/ 这个地址。
production 生产环境 , 和上面 vue.config.js 配置的 prod-server 相对,打包之后访问 http://localhost:8887/ 需要注意的是打包之后 Vue 的代理就失效了,需要 nginx 将后台服务代理到同一个端口上。
封装axios请求。
import axios from 'axios'
const baseUrl = process.env.VUE_APP_BASEURL
class HttpRequest {
constructor(baseUrl){
this.baseUrl = baseUrl
}
getDefaultConfig(){
const config = {
baseURL: this.baseUrl
}
return config
}
request(options){
const instance = axios.create()
options = Object.assign(this.getDefaultConfig(), options)
return instance(options)
}
}
export default new HttpRequest(baseUrl)
nginx.conf
location /server {
root /data;
index index.html;
autoindex off;
}
location /prod-server
{
proxy_pass http://127.0.0.1:8887;
}
3、baseURL的作用
看了很多文章设置baseURL都是用来区分开发和部署环境的,这个用法没有问题,而且确实很方便。
#相对地址
.env.development
VUE_APP_BASEURL=/dev-server
#绝对地址
.env.production
VUE_APP_BASEURL=http://127.0.0.1:8887/prod-server
baseURL还有一个作用就是直接请求原地址。
开发时配置 proxy 的 name 时请求的是基于 VUE 代理的相对地址
只需要将baseURL改成全路径。
这时候浏览器 Network 的 Request URL 就由原来的请求代理地址,变成了前端直接请求地址。
4、使用场景
用全路径 baseURL 的场景通常是在请求外站请求,且服务器访问不到的情况下,此时使用全路径 baseURL 就可以解决这个问题。
如果设置全路径 baseURL 之后,请求接口提示跨域,且增加跨域参数无法解决的情况下,有如下解决方案:
1、修改谷歌浏览器的安全性。
2、部署一个可以请求此地址的前端。
3、使用外壳访问。
推荐3。
更多推荐
所有评论(0)