I send a request to my API with advancedFetch. This works, however, I want to know if it is possible to send a parameter without defining it in the URL. Are there any smart ways of doing this?

I tried researching it but I'm not sure I'm using the right keywords for what I'm trying to do.

This is where I set off my request (the value is from a modal input field):

setNewUserName(userName) {
        this.setState({newUserName: userName});

        advancedFetch('/api/users', {
            method: 'POST',
            body: JSON.stringify({}),
            credentials: 'include',
            // I've tried sending the param here
            userName: userName,
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(() => {
                this.loadUsers();
            })
            .catch(err => {
                //error handling
            });
    }

In my controller I defined the route and implemented function like this:

index.create = (req, res, next) => {
        let userName = req.params.userName;

        console.log(userName);

        user
            .create(userName)
            .then((response) => {
                res.send(response);
            })
            .catch((err) => {
                next(err);
            });
    };

router.post('/users', index.create);

And then in my service.js I write the data to my database:

create: function(userName){
            userName = userName

            return query(`INSERT INTO ${tableName} (user) VALUES (?, ?)`, [1, userName])
                .catch(err => {
                    app.logger.error('[Users] failed to create a user', err.message);
                    return Promise.reject(new Error('failed to create user'));
                });
        },

I always get an undefined userName, do I have to create a route with the value at the end?

2 Answers

0
Jeremy Püringer On Best Solutions

Yes, you can actually do it this way:

In the frontend call you can send the parameter through the body like so

body: JSON.stringify({userName: userName})

And then in your controller what you want to do is to directly access the paramter from the body:

let userName = req.body.userName;

And now it's not undefined anymore :)

1
Tharkius On

You're receiving userName as undefined, because you're sending the request with JSON-encoded data, rather than URL parameters and the same logic doesn't apply for that case.

Luckily there's an easy way to solve your problem, using expressjs body-parser package. It's very easy to use.

This is how you initialize it:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

And this is how you would read "userName" in your router function:

index.create = (req, res, next) => {
        let userName = req.body.userName;

        console.log(userName);

        user
            .create(userName)
            .then((response) => {
                res.send(response);
            })
            .catch((err) => {
                next(err);
            });
    };

And btw, when you're calling advancedFetch, you should actually be doing this:

body: JSON.stringify({newUserName: userName}),