0

So, I have a nodejs app running on a webhosting. I have created a database and added a user to it and gave all privileges to it as well. now when using postman, I try to poat data, it is not added to the mysql database instead i get back this error:

{ "message": "Error executing query", "error": { "code": "ER_HOST_NOT_PRIVILEGED", "errno": 1130, "sqlMessage": "Host '127.0.0.1' is not allowed to connect to this MySQL server", "fatal": true } }

here is my server code:

const mysql = require("mysql");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

// Creating connection to the already created database, that is already on the server
const connection = mysql.createConnection({
  host: "localhost",
  user: "amtatrad_root",
  password: "pass",
  database: "amtatrad_youth_survey"
})

// Connect to the database
connection.connect(function (error) {
  if (error) {
    console.error('Error connecting to database: ', error);
    // Don't just throw the error. Instead, set a flag or handle the error in some other way.
  } else {
    console.log("Connected to database");
  }
});


// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.post("/server/", function (req, res) {
  let name = req.body.name;
  let age = req.body.age;

  let sql = "INSERT INTO user_data(name,age) VALUES(?,?)";
  connection.query(sql, [name, age], function (error, result) {
    if (error) {
      console.error(error);
      res.status(500).json({ message: 'Error executing query', error: error });
    } else {
      res.send({ message: 'User added with ID: ' + result.insertId });
    }
  });
});


const port = process.env.PORT || 3000;
app.listen(port, function() {
    console.log(`App is listening on port ${port}`);
});


I want to post name and age, data in database.

I have send

{ "name": "Talha", "age": 15 }

to the server via postman but getting error.

  • I'm guessing you created the user as `amtatrad_root@localhost`, but the Node.js connector silently replaces "localhost" to "127.0.0.1" and that means it isn't connecting as the user you created. In MySQL, a user "@localhost" is literally a distinct user from the same user name "@127.0.0.1", because localhost means to connect via UNIX domain socket instead of TCP/IP. Do you get the same error if you try to connect with `mysql -h 127.0.0.1 -u amtatrad_root -p`? – Bill Karwin Jun 21 '23 at 01:51

0 Answers0