PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

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

 October 13, 2022     axios, express, mongodb, mongoose, reactjs     No comments   

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
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing