VUE3.0中使用proxy遇到问题:Uncaught (in promise) Error: Request failed with status code 404

404
遇到问题首先缩小范围确定问题原因。
我用postman调接口有正确的返回值,说明与后台无关;肯定是前端配置问题;报404那有可能是接口问题,查询接口是否正确,嗯?……我查不出来!查询请求头信息,发现请求地址是正确的,这里就触及到了我的知识盲点:pathRewrite的使用

控制台
Request URL: http://localhost:8888/fundq/queryAssetListPage
Request Method: POST

首先与后台通信需要将main.js中使用到mock的信息注释掉,因为axios与mock会有冲突。

import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
// import '@/permission' // permission control

//以下代码注释
// import { mockXHR } from '../mock'
// if (process.env.NODE_ENV === 'production') {
//   mockXHR()
// }

// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
Vue.use(ElementUI)
Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

以下为我在vue.config.js中设置proxy代理的代码片段:

 proxy: {
   '/fundq': {
     target: 'http://192.168.106.88:9888',	//目标地址
     changeOrigin: true,	//是否跨域,默认false
     ws: true, 	//是否代理websockets
     pathRewrite: {		//重写路径
       '^/fundq': ''   //此处为问题原因,正确写法应为: '^/fundq': '/fundq'
     }
   },
 }

解释一下原因:

首先,在proxy模块中设置了‘/fundq’,target中设置服务器地址+端口号,然后我们在调用接口的时候,就可以全局使用‘/fundq’,这时候‘/fundq’的作用就相当于一个唯一标识,比如接口地址是 http://192.168.106.88:9888/fundq/queryAssetListPage,那我们在调用接口时可以直接写为/fundq/queryAssetListPage,系统会自动识别proxy中/fundq标识中的target地址并拼接在一起。

那pathRewrite是用来干嘛的呢,这里的作用,相当于是替换‘/fundq’,如果接口中没有/fundq,那就直接置空,就像我上面代码一样,但是我的接口中有/fundq,这时候我置空后真实的地址就变成了 http://192.168.106.88:9888/queryAssetListPage,与真实接口不一致,这就导致了接口错误,报错404;如果接口中有/fundq,那就得写成{‘^/fundq’:‘/fundq’},可以理解为一个替换路径、重写路径或者重定向的功能。

还有一种解决办法就是不设置pathRewrite参数,使用默认设置就可以:

 proxy: {
   '/fundq': {
     target: 'http://192.168.106.88:9888',
     changeOrigin: true,
   },
 }

当修改了vue.config.js中的内容后,一定要重新启动服务yarn start 或者npm run dev之后,修改的内容才会生效

发布了45 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ThisEqualThis/article/details/101053555