rainydaymatt
rainydaymatt

Reputation: 630

Undefined body in Node/Express API using bodyParser when accessed by fetch or axios

I'm making a call to an API in Node/Express in a React app, and regardless of where I put the fetch/axios call, my parsed body shows as undefined in my controller. I spent yesterday working with fetch, but tried axios for a change today, and here's the request:

axios({
    method: 'post',
    url: 'http://localhost:3000/users/sign_in',
    data: {
        email: "[email protected]",
        password: "xxxxxxx"
    }
})
    .then(data => console.log(data))
    .catch(err => console.log(err));

Now, here's the tricky part: console.log() statements in the Node controller AND the query file do trigger, so there's not a problem with the routing, and when I configure the query file to simply send a resource at random, ignoring the intended logic of searching by a body field, everything returns fine. But both fetch and axios result in undefined values for the req.body and any attribute therein. For instance, this action in the controller:

signIn(req, res, next) {
    let user = {
        email: req.body.email,
        password: req.body.password
    };
    console.log("1: " + Object.keys(req.body));
    console.log("2: " + req.body.email);
}

Will result in the following log to the console:

1: [object Object]
2: undefined

But a call to Object.keys() for the object in question returns an empty string.

I am using bodyParser, but as other questions have pointed out, that must be initialized before any route declaration - which I'm doing (I've abstracted configuration into a main-config.js file and a route-config.js files, and main contains bodyParser and is initialized first).

I'd greatly appreciate any help, and will happily provide more information and code snippets.

Edit: API code https://github.com/RainyDayMatt/abbas-tables-node-express-api/tree/mrh-add-user-code

Upvotes: 0

Views: 88

Answers (1)

rainydaymatt
rainydaymatt

Reputation: 630

So, I had implemented bodyParser incompletely. I had set up app.use(bodyParser.urlencoded({extended: true})) when initializing my main config file, but not app.use(bodyParser.json()).

Upvotes: 3

Related Questions