Vue axios Post请求 403 解决之道

2023-12-27 20:12:28
前言:

刚开始请求的时候报 CORS 错误,通过前端项目配置后算是解决了,然后,又开始了新的报错 403 ERR_BAD_REQUEST

后端的 Controller 接口代码如下:

@PostMapping(value = "/login2")
    @ResponseBody
    public LoginReq login2(@RequestBody LoginReq req, HttpServletRequest servletRequest, HttpServletResponse response) {
        System.out.println("---- login2 ----- userName = " + req.getUserName());
//        // 设置js请求跨域解决
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Methods", "GET, PUT, OPTIONS, POST");

        String userCode = servletRequest.getHeader("userCode");

        String accessToken = servletRequest.getParameter("accessToken");
        System.out.println("---- login2 --------------- accessToken = " + accessToken+" , userCode = " + userCode);
        String user = JSONObject.toJSONString(req);
        System.out.println("---- login2 ----- user = " + user);
        System.out.println("---- login2 -----  birthday = " + req.getBirthday());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = null;
        try {
            date = simpleDateFormat.parse(simpleDateFormat.format(req.getBirthday()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("date = " + simpleDateFormat.format(date));
        req.setBirthday(new Date());
        // 获取 cookie
        Cookie[] cookies = servletRequest.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                System.out.println("cookie >> name = " + name + " , value = " + value);
            }
        }
        if (req.getUserName().isEmpty() || req.getPwd().isEmpty()) {
            throw new RuntimeException("userName or pwd is empty");
        }
        return req;
    }

前端的调用代码如下:

 axios({
                    method: 'POST',
                    url: 'login/demo_war_exploded/login2',
                    data: JSON.stringify(
                        {
                            'userName':"朱",
                            'pwd':"pass1234!",
                            'birthday':"2022-12-06"
                        }),
                    headers: {
                        'Content-Type' : 'application/json'
                    }
                }).then(response => {
                    console.log(response)
                }).catch(function (error) {
                        console.log(error)
                })
解决跨域问题的前端配置:
 proxy: {
     "/login" :{
        target: "http://localhost:8180/",
        changeOrigin: true,
        //ws: true,//websocket支持
        secure: false,
        pathRewrite: {
          "^/login": ""
        },
       
      }
 }

403 报错如下图:
在这里插入图片描述
网上搜索了一堆都不行,各种五花八门的答案,对我来说都是无效的。
直到后面问了一个前端的同事,他让我在配置跨域的地方加一行配置,结果就 OK 啦,

proxy: { //配置多个跨域
      "/login" :{
        target: "http://localhost:8180/",
        changeOrigin: true,
        //ws: true,//websocket支持
        secure: false,
        pathRewrite: {
          "^/login": ""
        },
        // 后面新增的配置
        onProxyReq(proxyReq) {
          proxyReq.removeHeader('origin')
        }
      }
    },

最后,成功的截图如下:
在这里插入图片描述

文章来源:https://blog.csdn.net/zhujiangtaotaise/article/details/135250318
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。