axios 如何在前端输入并向后端发送请求?

qyzbxkaa  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(140)

我正在开发一个基本的博客应用程序,它需要标题和帖子输入,我试图将两个输入并发送请求将它们添加到数据库中。当用户提交表单时发出请求。

import React, { useState } from "react";
import axios from "axios";

const CreatePost = () => {
  const [title, setTitle] = useState("");
  const [post, setPost] = useState("");

  const onChangeTitle = (e) => {
    setTitle(e.target.value);
  };

  const onChangePost = (e) => {
    setPost(e.target.value);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const newPost = {
      title: title,
      post: post,
    };
    console.log(newPost);
    axios("http://localhost:5000/add", newPost)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));
  };
  return (
    <form onSubmit={onSubmit} className="container">
      <div className="mb-3">
        <label className="form-label">Title</label>
        <input onChange={onChangeTitle} className="form-control"></input>
      </div>
      <div className="mb-3">
        <label className="form-label">Write Post</label>
        <textarea
          onChange={onChangePost}
          className="form-control"
          rows="15"
        ></textarea>
      </div>
      <button type="submit">POST</button>
    </form>
  );
};
export default CreatePost;

添加内容的post请求是:

app.post("/add", (req, res) => {
  const title = req.body.title;
  const post = req.body.post;
  const newPost = new Post({ title, post });
  newPost
    .save()
    .then(() => res.json("Post added"))
    .catch((err) => res.status(400).json("Error:" + err));
});

错误代码:

GET http://localhost:5000/add 404 (Not Found)
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
aiqt4smr

aiqt4smr1#

您正在发送GET请求:

GET http://localhost:5000/add 404 (Not Found)

但是服务器端代码需要一个POST请求:

app.post("/add", (req, res) => {

改为发送POST请求:

axios.post("http://localhost:5000/add", newPost)

相关问题