CORS Missing Allow Origin

自用小总结

问题出现背景:前后端交互
问题描述:脚本无法获取响应主体(原因:CORS Missing Allow Origin
问题分析:前后端交互数据形式不匹配
自我检查:用 postman 检查后端接口是否能用,排除前端和后端其中一个
尝试更改
1. 前端是form-data / x-www-form-urlencoded数据,后端则需要使用@RequestParam

2. 前端是application/json数据,后端则需要使用@RequestBody

3. 后端尝试添加

1. , HttpServletResponse response
2. response.setHeader("Access-Control-Allow-Origin", "*");

位置在controller里面 ,例如 :
@PostMapping("/login")
public Result<User> loginController(@RequestParam String uname, @RequestParam String password, HttpServletResponse response){
        User user = userService.loginService(uname, password);
        if(user!=null){
            response.setHeader("Access-Control-Allow-Origin", "*");
            return Result.success(user,"登录成功!");
        }else{
            return Result.error("123","账号或密码错误!");
        }
    }       

4.前端请求添加请求头

 this.axios({
            url: "/user/login",               // 请求地址
            method: "post",                   // 请求方法
            headers: {                         // 请求头
              "Content-Type": "application/json",
            },
            params: {                          // 请求参数
              uname: this.ruleForm.uname,
              password: this.ruleForm.password,
            },
          })

5.前端请求参数应该是paramse 还是 data,是否与后端接收 controller 相匹配

你可能感兴趣的:(前后端结合,小白学习记录,前端,json,后端)