问题描述
已经在vue项目的config/index.js配置了proxyTable的路径重写,为什么在后端Controller的路径上还要加上/api才能访问?
问题出现的环境背景及自己尝试过哪些方法
前端接收后端返回的验证码,但是报404的错。只能在Controller的路径开头加上字段api才能正常访问
相关代码
config/index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
//1.如发送请求/api/xxx,此时请求拦/api
'/api': {
// 2.路径转发,此时请求地址变为http://localhost:8088
target: 'http://localhost:8088',
changeOrigin: true,////请求改变源,此时nginx可以获取到真实的请求ip
//3.路径重写,此时请求变成了http://localhost:8088/xxxx,
pathRewrite: {
'^/api': ''
}
}
},
views/reg.vue
getImage() {
const _this = this;
this.axios.get("/user/getImage").then((res) => {
console.log(res);
_this.src = "data:image/png;base64," + res.data.image;
_this.key = res.data.key;
})
},
Controller
@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
//生成验证码
@GetMapping("/getImage")
public Map<String, String> getImage(HttpServletRequest request) throws IOException {
Map<String, String> result = new HashMap<>();
....省略.....
}
}
你期待的结果是什么?实际看到的错误信息又是什么?
这是在Controller路径上加上api后
//生成验证码
@GetMapping("/api/user/getImage")
public Map<String, String> getImage(HttpServletRequest request) throws IOException {
Map<String, String> result = new HashMap<>();
CreateImageCode createImageCode = new CreateImageCode();
以下是另一个正常的项目,它在Controller中不用加api也能访问
确保一下你请求的地址,是否和你本地启动的代理服务器地址相同。比如说启动的是
http://localhost:8080
但是你代理的host
(不是target
)为http://localhost:8088
然后是排除问题是否是路径重写导致的,比如说去除请求URL中的
/api
看看请求是否正常,或者是否被跨域限制。如果是的话,得提供的
VueCLI
版本,我印象中现在的VueCLI
提供的代理只有devServer.proxy
并没有dev.proxyTable
。所以可能是VueCLI
早期版本,或者自己实现的脚手架。另外一个就是如果没有必要,前端代码中的
/api
就不需要添加,因为没有配置多个代理的需求。所以也就不需要重写请求路径了。