Animus
Animus

Reputation: 853

Why axios post in react is not read by the node server, when params are sent as object?

The params are sent. I can see the endpoint triggered, and dev tools display them. However, query params are not received by the server or interpreted incorrectly. Simple axios.post:

async function login(username, password) {
    return await axios.post(LOGIN_URL, {
            username,
            password
        },
    );
}

This situation is completely different if I'm just writing the query by hand, everything is received:

axios.post(LOGIN_URL + `?username=${username}&password:${password}`);

I want to use my bodyParser in educational purposes. Interpretation is as simple as possible with just 4 logs:

function bodyParser (req, res, next) {
    const body = url.parse(req.url).query;

    console.log(req.url); // /auth
    console.log(req.query); // {}
    console.log(req.body); // undefined
    console.log(req.params); // {}

    res.body = body;
    next();
}

The app:

import express from 'express';

import cors from 'cors';
import bodyParser from './middlewares';

import auth from "./routes/auth.route";

const app = express();

app.use('/', cors());
app.use('/', bodyParser);

app.use('/auth', auth);

export default app;

Upvotes: 0

Views: 107

Answers (2)

Chris Gong
Chris Gong

Reputation: 8229

I believe there is an issue with how you're calling axios.post(...). Assuming that when you call axios this way and it works:

axios.post(LOGIN_URL + `?username=${username}&password:${password}`); 

The username and password variables passed to axios.post(LOGIN_URL, {username, password}) are string variables. Therefore, you forgot to key the values like so,

async function login(username, password) {
    return await axios.post(LOGIN_URL, {
            'username': username,
            'password': password
        },
    );
}

Now in your bodyParser function, you should be able to access these variables passed in via req.params.username and req.params.password.

Upvotes: 0

Brant
Brant

Reputation: 1788

async function login(username, password) {
return await axios.post(LOGIN_URL, {
        username,
        password
    },
);
}

That's sending username and password in the req.body. So in Node, you need to be checking req.body

A Url like so:

http://someurl.com/api?username=a&password=b

You pick those variables up in req.query.

A Url like so:

http://someurl.com/api/people/some_id_here

You pick that ID up in req.params.

Upvotes: 2

Related Questions