Home > Software design >  Why is this POST request failing from Postman?
Why is this POST request failing from Postman?

Time:09-26

Backend of my app is deployed on Heroku using Cleardb addon.

Below is the Backend code: For what I can tell it is hitting the POST requst.

const express = require('express');
const cors = require('cors');
//const mysql = require("mysql");
//this was the old way and did not support secure password 
mysql = require('mysql2');


const app = express();

const port = process.env.PORT || 8000

/*
local connection 

const db =  mysql.createConnection({
    connectionaLimit: 50,
    user:'root',
    host: 'localhost',
    password:'',
    database:'sys',
    port: 3306
});

*/


const db =  mysql.createConnection({
    connectionaLimit: 120,
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    password: process.env.DB_PASSWORD,
    database: process.env.DATABASE,
    port: 3306
});


app.use(cors());


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

//SQL connection test
db.connect((err) => {
    if (err) console.error(err);
    console.log('MySQL Connection Established.');
  });
  
/* not used get request
app.get('/', (req,res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello back');
}

);
*/


app.post('/' , (req,res) => {
    const {email, name, question} = req.body;
    res.header("Access-Control-Allow-Origin", "*");
    console.log(`Your Email is ${email} and your name is ${name} and your ${question}`);



//MYSQL updating table

db.query("INSERT INTO customer_questions (name, email, question) VALUES (?,?,?)",
    [name, email, question], (err,result)=> {
        if (err) {
            console.log(err)
        }else {
            res.send('data sent')
        }
        db.end();
    }
    );


});
 


app.listen(port);
console.log(`server is listing on ${port}`);

This is the error log. From what I can tell it the server runs and then stops and the post request hits status 500. I can tell why this is happening.
enter image description here

Post request using POSTMAN showing body.
enter image description here

Any help on this would be helpful. The MYSQL connection works both locally and through Heroku.

CodePudding user response:

Use a connection pool and don't close the connection:

db.end();

You can run querys on the pool object and it will take care of opening/closing connections for you.

  • Related