0

// START EIDT:

Solution was (thanks to mr. Hawkeye @robertklep) the name "body" in my post request in axios on the client side.

// END EIDT:

I'm currently building an application with React as the frontend and Express as backend.

For API calls I'm using axios. My APIhas been working fine, but all of the sudden with no obvious change my post request body is not being sent to the backend.

In my index.js I had the following:

app.use(bodyParser.json());

but also tried with

app.use(express.json())

Client side function calling my post request:

 const checkForExistingUserData = async () => {
        if (user) {
            const body = {
                caseId: user['caseId']
            }

            await postRequest({request: body}, commonApiLocations["userDataLookUp"])
    }
}

My client side call is being call this way:

export function postRequest(body, url) {

        console.log(body) // Logs correct body with my data inside

        const config = {
        method: 'post',
        url: masterEndPoints['expressEndPoint'] + url,
        headers: {
            'Content-Type': 'application/json',
        },
        body // should be called "data" (see edit in top)
    };
    return axios(config);
}

Express route endpoint function:

route.post('/api/users/checkExistingUserData', async (req, res) => {

    try {
        const request = req.body.request;

        console.log("request: ", request); // Gives undefined

        if (request['caseId']) {
            let result = await checkIfExist(tableNames['TableName'], {'caseId': request.caseId})
            res.status(200).send(result);
        } else {
            res.status(200).send(false)
        }
    } catch (error) {
        res.status(500).send('En error occurred on the server')
    }
});

When I console.log on on the client side I see my request with the data that I expect to see.

When I console.log on the server I get an undefined.

When I console.log req.body I get "{}"

Any reasons for this error? I'm completely dumbfounded by this.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Gustav Vingtoft
  • 355
  • 2
  • 16
  • https://expressjs.com/en/api.html#req.body — Have you read the second sentence of the documentation for `req.body`? – Quentin Jun 23 '22 at 13:42
  • Have you got app.use(express.json()) on your index file ? – subodhkalika Jun 23 '22 at 13:45
  • I have app.use(bodyParser.json()); but have also tried with app.use(express.json()) Still the same result – Gustav Vingtoft Jun 23 '22 at 13:48
  • Then it looks like the data you are posting doesn't match the shape of the data the server is expecting, but you haven't shown us what you are posting. – Quentin Jun 23 '22 at 13:53
  • @Quentin can you reopen the question since its not the samme error and therefore response in the question associated with this question. – Gustav Vingtoft Jun 23 '22 at 13:54
  • The question should remain closed, just for a different reason, it lacks a [mcve] – Quentin Jun 23 '22 at 13:55
  • @Quentin see my latest edit. Is this sufficient for you? – Gustav Vingtoft Jun 23 '22 at 13:57
  • Where exactly did you put `app.use(express.json())`? It needs to be declared before your routes. – robertklep Jun 23 '22 at 14:03
  • @robertklep at the top of my index.js file in express right after const app = express() and before my routes. – Gustav Vingtoft Jun 23 '22 at 14:04
  • Btw when I console.log req.body in my route I dont get an undefined, but an empty object "{}" – Gustav Vingtoft Jun 23 '22 at 14:04
  • 1
    @GustavVingtoft axios uses `data`, not `body` – robertklep Jun 23 '22 at 14:12
  • https://axios-http.com/docs/api_intro – Dave Newton Jun 23 '22 at 14:14
  • @robertklep there we go. Once I changed body to data on my clientside it worked. Wild. Thank you. – Gustav Vingtoft Jun 23 '22 at 14:16
  • That is actually pretty wild and unexpected tbh, since I'm passing a reference and not hardcoding an body object with a key named data. But apparently the reference itself must be named "data"? I didn't change any "hardcoded" keys at all, only the parameter in the post request function. Actually I don't get this at all, even though it works. – Gustav Vingtoft Jun 23 '22 at 14:20
  • @Quentin can you remove duplicate question since this is about the different issues and solutions? – Gustav Vingtoft Jun 23 '22 at 14:29
  • 1
    "That is actually pretty wild and unexpected tbh, since I'm passing a reference and not hardcoding an body object with a key named data." — `{ body }` means `{ "body": body }`, it just a short hand. You're creating a key named `body`. – Quentin Jun 23 '22 at 14:31
  • "can you remove duplicate question since this is about the different issues and solutions?" — You got a property name wrong. That's an error on par with a typo … which is another reason questions here get closed (they don't help future users since they aren't searchable). So if it was reopened, it would just have to be closed again. – Quentin Jun 23 '22 at 14:32

0 Answers0