微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的 axios 发布请求不起作用并发送空字符串?

如何解决为什么我的 axios 发布请求不起作用并发送空字符串?

一个简单的应用程序上制作了一个简单的聊天组件来学习完整的堆栈,但我不确定为什么当我在 react 上使用 axios 时我的帖子请求不起作用,即使当我在邮差。所以,我认为问题出在我的代码中。在邮递员中,当我在键中输入用户名和消息并为它们提供字符串值时,它可以工作(请参阅底部的最终 console.log)。但是当我使用我的代码这样做时,它发送的是空值而不是我传递的字符串值。即使我使用 JSON.stringify ,但不知何故 axios 最终会发送 [object] ,这是问题吗?如果没有,我做错了什么?非常感谢你。这是我的代码

updateChat = e => {
        e.preventDefault();
        const { chat,username,chats } = this.state;

        this.setState({ chat : e.target.value });

        chats.push(chat);

        console.log("username: " + username + ",message: " + chat)

        var body = { 
            username : username,message : chat };

        console.log("body: " + body)

        axios({
            method: 'post',url : 'http://localhost:8080/api/chats/add',data: body
        })
        .then(function (response) {
            console.log("Submitted: " + response);
        })
        .catch(function (error) {
            console.log("Post error: " + error);
        });
        this.pullChats();
    }

pullChats() {
        axios.get('http://localhost:8080/api/chats')
        .then(res => {
            this.setState({ chats : res.data });
            console.log(res.data); 
        })
        .catch(function (error) {
            console.log("Error: " + error);
        });
    }

<div>
                {chats.map(chats =>
                <span className="badge badge-pill badge-warning p-3">
                    <p>{chats.message}</p> Username: <span className="text-green">{chats.username}</span>
                </span>)}
                <p>Posting as(username): <span className="text-green">{username}</span></p>
                <input type="text" value={chat} onChange={this.handleChatAddition}/>
                <button className="btn btn-light" onClick={this.updateChat}>Send</button>
            </div>

当我使用 Console.log 时:

username: USERNAME,message: testest

第二行:

body: {"username":"USERNAME","message":"testest"}

第三行:

Submitted: [object Object]

第 4 行:(ID 为 1、2、6、7 和 8 的对象是从邮递员创建的,而其余的对象是使用 axios 创建的。出于某种原因,当我使用 axios 时,即使它们是字符串,我不知道为什么)

(15) [{…},{…},{…}]
0: {id: 1,username: "UsernameABC",message: "This is my question"}
1: {id: 2,username: "User2",message: "Okokok"}
2: {id: 3,username: null,message: null}
3: {id: 4,message: null}
4: {id: 5,message: null}
5: {id: 6,username: "testesttesttrtr",message: "hitest"}
6: {id: 7,message: "hitest"}
7: {id: 8,message: "hitest"}
8: {id: 9,message: null}
9: {id: 10,message: null}
10: {id: 11,message: null}
11: {id: 12,message: null}
12: {id: 13,message: null}
13: {id: 14,message: null}
14: {id: 15,message: null}
length: 15
__proto__: Array(0)

顺便说一句,这是我的后端:

控制器:

@CrossOrigin(origins="*")
@RestController
@RequestMapping("api/")
public class ChatController {
    
    @Autowired
    private ChatRepository chatRepository;
    
    @GetMapping("chats")
    public List<Chat> getChats(){
        return this.chatRepository.findAll();
    }
    
    @PostMapping("chats/add")
    public Chat addChat( Chat newChat) {
        return chatRepository.save(newChat);
    }

}

型号:

@Entity
@Table(name="users")
public class Chat {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    @Column(name = "username")
    private String username;
    
    @Column(name = "message")
    private String message;
    public long getId() {
        return id;
    }
    
    public Chat() {
        
    }
    
    public Chat(String username,String message) {
        super();
        this.username = username;
        this.message = message;
    }



    public void setId(long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

存储库:

@Repository
public interface ChatRepository extends JpaRepository<Chat,Long> {

} 

应用:

@

SpringBootApplication
public class ChatBackendApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ChatBackendApplication.class,args);
    }

    
    @Autowired
    private ChatRepository chatRepository;
    
    @Override
    public void run(String... args) throws Exception {
        this.chatRepository.save(new Chat("UsernameABC","This is my question"));
        this.chatRepository.save(new Chat("User2","Okokok"));
        
    }

}

解决方法

您是否尝试过以下方法使用 axios 执行发布请求?

axios.post('http://localhost:8080/api/chats/add',{ username: username,message: chat })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

类似于您的获取请求

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?