#author("2023-09-13T11:12:34+08:00","default:Admin","Admin") #author("2023-10-24T14:27:04+08:00","default:Admin","Admin") [[Vue]] &color(red){※前提条件:本文基于 Vue 2.0 创作}; #contents * 概要 [#ueb5c50a] 在项目开发过程中,一般都是在同一域名下进行接口联调,且不存在跨域,但是当我们在使用vue-cli进行项目打包的时候,在本地启动服务器后,比如本地开发服务下是 http://localhost:8080 这样的访问页面,但是我们的接口地址是 http://xxxx.com/save/index ,这样直接使用会存在跨域的请求,导致接口请求不成功,因此需要在打包的时候进行代理配置。 #codeprettify{{ dev: { // 静态资源文件夹 assetsSubDirectory: 'static', // 发布路径 assetsPublicPath: '/', // 代理配置表,在这里可以配置特定的请求代理到对应的API接口 // 例如将'localhost:8080/api/xxx'代理到'www.example.com/api/xxx' // 使用方法:https://vuejs-templates.github.io/webpack/proxy.html proxyTable: { '/api': { target: 'http://xxxxxx.com', // 接口的域名 // secure: false, // 如果是https接口,需要配置这个参数 changeOrigin: true, // 如果接口跨域,需要进行这个参数配置 pathRewrite: { '^/api': '' } } }, // 本地访问 http://localhost:8080 host: 'localhost', // can be overwritten by process.env.HOST }} 接口地址原本是 /save/index,但是为了匹配代理地址,在前面加一个 /api, 因此接口地址需要写成这样的即可生效 /api/save/index。 &color(red){注意:}; -"/api" 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 "/api", --而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 "/api" 转为 "/"。 --如果本身的接口地址就有"/api" 这种通用前缀,就可以把 pathRewrite 删掉。 #codeprettify{{ '/api': { target: 'http://192.168.0.73:8889/', //请求后台接口 // secure: false, // 如果是https接口,需要配置这个参数 changeOrigin: true, // 如果接口跨域,需要进行这个参数配置 // pathRewrite: { // '^/api': '', // 重写请求 // }, }, }} 所以按照上面的ProxyTable的写法,实际服务的配置路径里面不要出现 API * Tips [#y33986a7] 如果api的路径里面不是api开头的,比如,下面的something后面跟着api的 http://wwww.exam.com/something/api/login #codeprettify{{ '/api': { target: 'http://wwww.exam.com', //域名 changeOrigin: true, // 如果接口跨域,需要进行这个参数配置 pathRewrite: { '^/api': '/something/api', // 重写请求 }, }, }} #hr(); コメント: #comment_kcaptcha