Unable to use body values in INSERT statement

83 views Asked by At

I have a post route that expects to be sent body value name to be supplied in JSON format.

My server.js includes:

app.use(express.json({ extended: false })); 

Here is an how the route looks:

router.post('/',
[
    check('name', 'Name is required!')
        .not()
        .isEmpty(),
],
async (req, res) => {
    const validationErrors = validationResult(req);
    if (!validationErrors.isEmpty()) {
        return res.status(400).json({ validationErrors: validationErrors.array() });
    }
    else {
        try {
            await odbc.connect(cn, (error, connection) => {
                console.log(req.body.name)
                connection.query(
                    "INSERT INTO test.amessages(name) VALUES(:req.body.name)",
                    (error, result) => {
                        if (error) {
                            throw error;
                        }
                        return res.status(200).json({ result });
                    }
                );
            });

        }
        catch (error) {
            console.error(error);
            return res.status(500).json({ msg: 'Server Error' });
        }
    }
});

The console.log before the variable gives me the correct value supplied to the route. Typically when using other tools that target sqlserver I have been able to put in ${req.body.name} and that would work. In this case that and the following have not worked - (req.body.name), :req.body.name, (req.body.name) and other various combinations.

Here is a look at how I am supplying the values to the route:

{
    "name": "Test"
}

How can I utilize the body values in the Insert statement?

1

There are 1 answers

4
eol On BEST ANSWER

According to the documentation you can pass a paramter array to the query-function which will be bound to the ? values:

connection.query("INSERT INTO test.amessages(name) VALUES(?)",
                    // actually with the json you provided it seems you rather want to use req.body.name
                    [req.body.test],
                    (error, result) => {
                        if (error) {
                            throw error;
                        }
                        return res.status(200).json({ result });
                    }
                );