I had install xampp vm on os x
The view of xampp like this :
I access phpmydmin like this :
I want to connect it with my project express js
I try like this :
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const request = require("request");
const https = require('https');
const mysql = require('mysql');
//create database connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'myappexpress',
port: '8080'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
const app = express();
app.use(bodyParser.json());
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
//show all customers
app.get('/api/customers',(req, res) => {
let sql = "SELECT * FROM customers";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Then I call http://localhost:5000/api/customers from postman
On the command prompt exist error like this :
How can I solve this problem?
2
Answers
phpMyAdmin is a web-based interface to allow administrators to manage a MySQL or MariaDB database installation. You can’t connect to it from Express JS because it doesn’t expose any API, it’s just a graphical application. You should instead try to connect directly to your MariaDB server instance. Doing so may be as trival as adjusting your connection port to the MySQL/MariaDB port of 3306.
I see that the port you are using is 8080 when that is the port of the apache web server to connect to the base, it changes the port of the mysql base, because this can be mistaken for being a default port,
try to remove the port so that the express database libraries take the port by default, for example
const conn = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ”,
database: ‘myappexpress’
});