vuecli3 设置proxy代理时,我下面这两种请求路径写法都分别报错404和302。
我的ip地址是51结尾的
后端地址是54结尾的
第一种:如果我在vue文件里面请求路径这样写,就会出现404的错误,如下图
vue文件
mounted () {
apiPost('/getUserInit.do', {})
.then((res) => {
console.log(res)
})
},
第二种写法,就会出现302重定向的问题如下图
vue文件
mounted () {
apiPost('http://192.168.XX.54:8080/XXX/getUserInit.do', {})
.then((res) => {
console.log(res)
})
},
第一种写法报错截图
疑问的是:请求的地址不应该是后端那个地址吗,为什么是我的ip地址。
第二种写法报错截图
以下是关于代理的其他文件的代码。
main.js
// 使用了全局配置的axios 将axios挂载到原型上
Vue.prototype.axios = axios
// 请求默认的域名——跨域配置_配置请求的根路径
axios.defaults.baseURL = '/api'
axios.js
// 自定义一个Axios实例化对象
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
// baseURL:process.env.BASE_URL,
// baseURL: 'http://192.168.XX.54:8080/XXX',
// baseURL: '/api',
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 50000,
// 设置跨域 Cookie
withCredentials: true
})
request.js
import http from './axios.js'
export const apiPost = (url, data) => {
return http({
baseURL: url,
method: 'post'
})
}
vue.config.js
// 跨域问题
devServer: {
open: true, // 自动打开浏览器
// 修复使用hostname访问,就会显示invalid host header。
disableHostCheck: true,
// 服务器地址主机名
// host:'0.0.0.0',
// 服务器端口号
// port:'8080/',
// 配置跨域
proxy: {
'/': {
// 这里后台的地址,
target: 'http://192.168.XX.54:8080/XXX',
// 如果要代理websockets
ws: true,
// 允许跨域
changeOrigin: true,
pathRewrite: {
// 使用 `/api` 代替 `target` 要访问的跨域的域名
'^/': ''
}
}
}
以上代码就这样,不知道问题是不是出在前端,我在这几个文件检查,却不知道哪里错了。
能成功代理并获取到接口数据 ! o(╥﹏╥)o【在这里花了老长时间了,虽说这代理不难,但是我却花了不少时间,还没完成那种……】
proxy: {
'/api': {
// 这里后台的地址,
target: 'http://192.168.XX.54:8080/XXX',
// 如果要代理websockets
ws: true,
// 允许跨域
changeOrigin: true,
pathRewrite: {
// 使用 `/api` 代替 `target` 要访问的跨域的域名
'^/api': ''
}
}
apiPost('/api/getUserInit.do', {})
.then((res) => {
console.log(res)
}) //这样试试