跨域时后端Controller的路径怎么写?

问题描述

已经在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<>();
         ....省略.....
}
}

你期待的结果是什么?实际看到的错误信息又是什么?

image.png
这是在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();

image.png


以下是另一个正常的项目,它在Controller中不用加api也能访问
image.png

阅读 1.6k
1 个回答

确保一下你请求的地址,是否和你本地启动的代理服务器地址相同。比如说启动的是 http://localhost:8080 但是你代理的 host (不是 target)为 http://localhost:8088

然后是排除问题是否是路径重写导致的,比如说去除请求URL中的 /api 看看请求是否正常,或者是否被跨域限制。
如果是的话,得提供的 VueCLI 版本,我印象中现在的 VueCLI 提供的代理只有 devServer.proxy 并没有 dev.proxyTable。所以可能是 VueCLI 早期版本,或者自己实现的脚手架。


另外一个就是如果没有必要,前端代码中的 /api 就不需要添加,因为没有配置多个代理的需求。所以也就不需要重写请求路径了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题