dumblessar
dumblessar

Reputation: 69

How to send data from react and use the request body in express, using Axios?

I use states to hold some form data in react, and what i want is, when i submit the form in react i send a post request using axios,and i want to use the form data in express. I tried req.body.params, req.body.data, req.body general,to access the request payload and they all returned undefined. Basically I want to access general(form data) in express. How can i do that?

note: the states are named general, and oneSuggestion, they are basic string states.

note:i searched similar questions for hours but none of them solved my question. if there was a solution, i couldn't find it, please excuse me.

edit: commented data, and put the states directly inside post.

React code:

      function handleSubmit(e) {
        e.preventDefault();
        console.log(general, suggestionsForCases);
        /*
                        let data = {
                        general: general,
                        oneSuggestion: oneSuggestion,
                        };
                        data = JSON.stringify(data);
                        console.log(data);
                        */

        let axiosConfig = {
        headers: {
            "Content-Type": "application/json;",
            "Access-Control-Allow-Origin": "*",
        },
        };
        axios
        .post(
            "http://localhost:8000/dict/",
            { general: general, oneSuggestion: oneSuggestion },
            axiosConfig
        )
        .then((res) => console.log("success, dictionary sent,", res))
        .catch((err) => {
            console.log(err.response);
        });
    }
    function handleInput(e) {
        if (e.target.name == "general") {
        setGeneral(e.target.value);
        console.log(general);
        }
        if (e.target.name == "oneSuggestion") {
        setOneSuggestion(e.target.value);
        console.log(oneSuggestion);
        }
    }

    return (
        <div>
        <form onSubmit={handleSubmit}>
            <label>
            general:
            <textarea name="general" onChange={handleInput}></textarea>
            </label>

            <label>
            suggestion:
            <input name="oneSuggestion" onChange={handleInput}></input>
            </label>
            <button type="submit">submit</button>
        </form>
        </div>
    );
    }
    export default AddDictionary;



        

express code:

    const express = require("express");
    const router = express.Router();

    const Dictionary = require("../database/category/dictionary");

    router.use(express.json());

    router.get("/", (req, res) => {
    console.log("success");
    res.json({ msg: "success"});
    });
    router.post("/", (req, res) => {
    console.log(req.body.general);
    res.json({
        msg: "success",
    });
    });

    module.exports = router;

Upvotes: 3

Views: 6041

Answers (2)

dumblessar
dumblessar

Reputation: 69

Ok, I found the problem. I deleted the axiosConfig from post, based on this source , and now this is the working code:

         axios
        .post(
            "http://localhost:8000/dict/",
            { general: general, oneSuggestion: oneSuggestion }
        )
        .then((res) => console.log("success, dictionary sent,", res))
        .catch((err) => {
            console.log(err.response);
        });

thank you guys for your help.

Upvotes: 2

Aaron
Aaron

Reputation: 161

You'll need middleware in order to parse the request and make it accessible in req.body. I've assumed you're using a version after 4.16 which introduced express.json() as middleware for this scenario. I'll update my answer if you're using an earlier version.

Example using your code as a starter:

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

app.use(express.json());

app.post('/', (req, resp) => {
  console.log(request.body.params);
});

app.listen(3000);

To explain, anything you post, aka let's say you posted the following object:

{
  fruit: 'apple',
  vegetable: 'onion'
}

After using the parser you'd access the posted data in req.body.fruit and req.body.vegetable.

Upvotes: 0

Related Questions