How to take input in front-end and send request to back-end?

Issue

I am working on a basic blog application and it takes title and post input
I am trying to take two inputs and send the request to add them to the database.
The request is made when the user submits the form.

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;

The post request to add the content is:

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));
});

Error:

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, …}

Solution

You’re sending a GET request:

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

But the server-side code is expecting a POST request:

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

Send a POST request instead:

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

Answered By – David

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published