“这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战”
本文主要讲接口转发,提供了两个服务器地址用于测试
先说接口转发怎么做,再说原理
怎么做
接口转发主要有两种情况:
-
第一种情况是,你前端自定义了一个前缀,后端没有这个前缀,转发的时候你需要去掉前端的前缀,一般用于访问接口。
-
第二种情况是,前端和后端都有个前缀,转发的时候不用去掉前缀。
以vue为例说明一下,在vue.config.js中加入以下代码
//接口服务器
const API_SERVER='http://111.229.14.189'
//文件服务器
const FILE_SERVER='http://111.229.14.189'
module.exports={
//只在开发时有效,打包后失效
devServer: {
open: true, //自动打开浏览器
proxy: {
'/file':{
target: FILE_SERVER, //开发环境后端接口地址
changeOrigin: true,
autoRewrite: true,
cookieDomainRewrite: true,
},
'/my-custom-prefix':{
target: API_SERVER, //开发环境后端接口地址
changeOrigin: true,
autoRewrite: true,
cookieDomainRewrite: true,
pathRewrite:{
'^/my-custom-prefix': ''
}
}
}
},
}
然后在main.js
中加入以下代码
//---------------测试接口转发
import axios from 'axios'
///http://localhost:8080/file/1.jpeg -> http://111.229.14.189/file/1.jpeg
axios.get('/file/1.jpeg').then(res=>{console.log('file response',res)})
///http://localhost:8080/my-custom-prefix/gk-api/util/test ->http://111.229.14.189/gk-api/util/test
axios.get('/my-custom-prefix/gk-api/util/test').then(res=>{console.log('api response',res)})
执行npm run serve
,在浏览器中可以看到两个接口都转发成功了
第一个接口长这样:http://111.229.14.189/gk-api/util/test
我本地要转发过去,我加了个前缀,/my-custom-prefix
(前缀是自己设置的,想设置啥都可以,反正最后要去掉)
当我访问的url带有 /my-custom-prefix
前缀时,全都转发到后端接口上面
即当我访问
http://localhost:8080/my-custom-prefix/gk-api/util/test
时,实际上访问的是
http://111.229.14.189/gk-api/util/test
因为前端自己加了个前缀,后端没有该前缀,所以转发时,要去掉前缀,去掉前缀使用pathRewrite
'/my-custom-prefix':{
target: API_SERVER, //开发环境后端接口地址
changeOrigin: true,
autoRewrite: true,
cookieDomainRewrite: true,
pathRewrite:{
'^/my-custom-prefix': ''
}
}
第二种情况,访问文件服务器,转发如下:
http://localhost:8080/file/1.jpeg -> http://111.229.14.189/file/1.jpeg
配置转发的时候,就不用加pathRewrite了,其他配置一样的。
原理是什么
服务器和前端启动的程序不同源,在浏览器存在同源策略的情况下,无法访问接口。
前端接口转发的处理思路是:启动一个和前端程序同源的代理服务器,前端程序发请求到代理服务器,代理服务器将请求转发到服务器(服务器之间不存在同源策略)
浏览器->服务器
变成 浏览器->代理服务器->服务器
需要注意的一点是:转发的时候,访问的是代理服务器,URL也是代理服务器的URL,不再是后端接口服务器。