我使用request.post向后端传递数据为什么后端接收不到了?

这是后端Controller代码


package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.controller.dto.cuserDTO;
import com.example.demo.entity.cuser;
import com.example.demo.mapper.cusermapper;
import com.example.demo.service.cuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.swing.text.AbstractDocument;
import java.sql.Struct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController  {
    @Resource
    private cusermapper cusermapper;
    @PostMapping
    public boolean login(@RequestBody cuserDTO cuserDTO)
    {System.out.println(cuserDTO.getCname());
        String username=cuserDTO.getCname();
        String password=cuserDTO.getCpassword();

        if(StrUtil.isBlank(username)||StrUtil.isBlank(password))
        {     System.out.println(username);
            return  false;

        }else {
            List data= cusermapper.login(cuserDTO);
            if (data==null){return false;}
            else {return true; }
        }}

    @GetMapping("/all")
    public List index(){
        return cusermapper.findAll();
    }
}

这是前端的数据和方法:

<script>
    import HelloWorld from '@/components/HelloWorld.vue'
    import request from "@/utils/request"
    export default {
        name: "login",
        data(){
            return{
                cuserDTO:{}
            }
        },
        methods:{
            shiyan(){
                this.$router.push("/Home")
            },
login(){
    let config = {
        headers: {
            "Content-Type": "application/json"
        },
    };
    request.post("/user",JSON.stringify(this.cuserDTO),config).then(res => {
        if(!res){
            console.log(res)
            console.log(this.cuserDTO)
            this.$message.error("登录失败")

        }else{
            console.log(this.cuserDTO)
            this.$router.push("/Home")

        }})
}
        }
    }
script>

你浏览器 F12 看下 网络那里实际上发出去的是啥

接收不到是什么意思,是连接失败还是请求失败,如果是请求失败,那你可以看看你发送的数据是什么了,后端接收的是body,你前端传的头

该回答引用GPTᴼᴾᴱᴺᴬᴵ
从前端代码看,您使用了axios的post请求,但是从后端代码看,使用的是SpringMVC的@PostMapping注解接收请求。

如果您的后端是基于SpringMVC的,建议使用以下方法来接收前端传递的数据:

1.前端代码:

request.post("/user", this.cuserDTO).then(res => {
    // 处理响应结果
});


2.后端代码:

@PostMapping
public boolean login(@RequestBody cuserDTO cuserDTO) {
    // 处理接收到的数据
}


其中,@RequestBody注解会将前端传递的数据自动转换为后端所需的对象类型,无需手动解析。

另外,建议使用浏览器的开发者工具来查看请求和响应的具体内容,以方便调试。

@PostMapping 路径都不写 咋接收呢??

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^