1

So I am trying to make a small api with MySQL and Express JS, after following a small tutorial online on how to use MySQL with Express I tried to make this api and send requests with the postman, to insert the data I sent using postman I used in my code the req.body.data syntax, I tried using tha classic SQL syntax of INSERT INTO table (col1, col2) VALUES (val1, val2) using interpolation for the request body and I also tried the SET ? as I saw in the tutorial I watched. When trying to send the request with postman I keep getting the Cannot read property 'title' of undefined error. How can I insert data that I send to the table with postman?

JavaScript

app.get('/addtodo' , (req, res) => {
    let sql = 'INSERT INTO todo SET ?'
    let post = {
        title: req.body.title,
        body : req.body.body,
        date: req.body.date,
        importance: req.body.importance
    }
    db.query(sql, post, (err, res) => {
        if(err) throw err;
        console.log('success');
        console.log(res);
    });
});

3 Answers 3

3

Use Post method instead get because you can not pass body in get method

app.post('/addtodo' , (req, res) => {
    let sql = 'INSERT INTO todo SET ?'
    let post = {
        title: req.body.title,
        body : req.body.body,
        date: req.body.date,
        importance: req.body.importance
    }
    ...
});
Sign up to request clarification or add additional context in comments.

Comments

0

GET request has no body, it contains only query or params

Comments

0

change app.get(...) to app.post(...) in javascript code..

in this case send POST request through postman

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.