Home > Software design >  Getting "undefined" when trying to post with EXPRESS on SQL database?
Getting "undefined" when trying to post with EXPRESS on SQL database?

Time:06-23

(still a beginner with sql and express)

I am trying to make a post request on my SQL database with express. When I try posting with Postman, I get a "TypeError: Cannot read properties of undefined".

Here's the code:

    app.post('/getperipherals', (req, res) => {
    let product = {
        product_name: req.body.product_name,
        product_type: req.body.product_type,
        product_brand: req.body.product_brand,
        product_description: req.body.product_description,
        product_url: req.body.product_url,
    };
    let sql = `INSERT INTO users (product_name, product_type, product_brand, product_description, product_url, register_date) values ('?', '?', '?', '?','?', now())`;
    let query = db.query(sql, product, (err, result) => {
        if(err) throw err;
        res.send(result)
    })
})

This is what my request looks like on postman:

{
"product_name": "Imprimante TEST",
"product_type": "printer", 
"product_brand": "Marque TEST",
"product_description": "This is a POST test", 
"product_url": "https://i.imgur.com/RwvdTpV.png" 
}

( a POST request, with my custom route -which is working-)

CodePudding user response:

app.post('/getperipherals', (req, res) => {
    let {product_name,product_type,product_brand,product_description,product_url } = req.body;
    let sql = `INSERT INTO users (product_name, product_type, product_brand, product_description, product_url, register_date) values (product_name,product_type,product_brand,product_description,product_url, now())`;
    let query = db.query(sql, product, (err, result) => {
        if(err) throw err;
        return res.send(result)
    });
});

Try this out let me know if it work or not for you

CodePudding user response:

EDIT

Finally found a way to get it to work: I used INTERT INTO SET

app.post('/getperipherals', (req, res) => {
let product = {
    product_name: req.body.product_name,
    product_type: req.body.product_type,
    product_brand: req.body.product_brand,
    product_description: req.body.product_description,
    product_url: req.body.product_url,
    };

let sql = "INSERT INTO peripherals SET ?";
let query = db.query(sql, product, (err, result) => {
    if(err) throw err;
    return res.send(result)
});

});

  • Related