Home > Mobile >  how to post form data to the server backend
how to post form data to the server backend

Time:06-21

Form.js

import "./form.css";
import React, {useEffect,useState} from "react";
import {addBeauty,deleteB} from "./beauty";
import Modal from "./Modal";
import axios from 'axios';


export default function CreateForm() {

    const [Name, setName] = useState("");
    const [Intro, setIntro] = useState("");
    const [isOpen, setIsOpen] = useState();

    const [backendData, setBackendData] = useState([{}]);

    useEffect(()=>{
        fetch("http://localhost:5000/api").then(
            response=>response.json()
        ).then(
            data=>{ setBackendData(data)}
        )
    },[]);


    const handleSubmit = (event)=>{
        event.preventDefault();
     
        axios.post("http://localhost:5000/api",{
            id: userList[userList.length - 1].id   1, Name:Name, Introduction:Intro
        }).then(res=>{
            console.log(res.data);
        })

    }




    return (
        <div className="container">
            
            <form className="add" onSubmit={handleSubmit} >
                <h2>User</h2>
                <label htmlFor= "name">Name</label>
                <input type="text"    value={Name}
                       onChange={(event) => {setName(event.target.value);}}/>
                <label htmlFor= "Intro">Introduction</label>
                <input type="text"   value={Intro}
                       onChange={(event) => {setIntro(event.target.value);}}/>

                <p></p>
                <p></p>

                <div className = "press">
                    <button  id = "1" type="submit">
                        Add Beauty
                    </button>
                    <button  id = "2"
                             onClick={clearForm}
                    >
                        Clear Form
                    </button>
                </div>
            </form>

            <br></br>
            <br></br>
            <br></br>

            <div className="display">
                {(typeof userData.user1 === 'undefined')?(
                    <h1>Loading</h1>):(
                    backendData.user1.map((user,i)=>{
                        return (
                            <div>
                                <h1> {user.Name}</h1>
                  
                                <button onClick={()=>{
                                    setIsOpen(user.id);
                                }}>View in popup</button>
                                <Modal open={isOpen === user.id} onClose={()=>setIsOpen(undefined)}>
                                    <h3> {User.Introduction}</h3>
                                </Modal>

                            </div>
                        );})
                )}

            </div>
        </div>
    );
}

Server.js

const express = require('express');
const app = express();

const cors=require("cors");

const corsOptions ={
    origin:'*',
    credentials:true,            //access-control-allow-credentials:true
    optionSuccessStatus:200,
}

app.use(cors(corsOptions)) // Use this after the variable declaration

app.get("/api",(req,res)=> {
    res.json({"user1":[
            {
                id: 1,
                Name: "Isabella",

            },
            
{
                id:2,
                Name: "Catalina
}
            

        ]})

});


app.listen(5000,()=>{
    console.log("Server started on port 5000");
})

I create a from using react. And I try to send the formdata to backend and insert the formdata into the data stored at backend using axios.post. But it doesn't work. I know it's because I didn't add the prefix of backend data "user1" in axios.post. But I am not sure how to do that. Could anyone help me with this?

CodePudding user response:

You have not created the route on the server correctly. You have opened a route for GETting "/api" but you need to open a route for POSTing

Replace this line:

app.get("/api",(req,res)=> {

with

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

CodePudding user response:

Hi Here you need to create one route for post API as below

app.post("/api",(req,res)=> {
    console.log(req.body) //here you got the requested data.
    res.send("Success !");

});
  • Related