My GET request works in localhost but not on my server. I tested it with Postman. My Hostinger is OVH. My DB is also hosted in OVH but it is not directly connected to the server. Here the code of the app :
const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql')
const { response } = require('express')
const app = express();
const PORT = process.env.PORT || 35707;
// My external DB mysql
const db_conn = mysql.createPool({
connectionLimit : 10,
host: 'Myhost',
port: 35707,
user: 'myUsername',
password: 'Mypassword',
database: 'mydb'
})
//this one works
app.get('/', (req, res) => {
res.json({ test: 'test'});
});
// this one also works
app.get('/all.json', (req, res) => {
db_conn.getConnection( (err, conn) => {
if(err) throw err
console.log(`connected as id ${conn.threadId}`)
conn.query(
"SELECT ID, [.....]",
(err, rows) => {
conn.release()
if(!err){
res.send({"table": rows});
}else {
console.log(err);
}
})
})
})
//this one works on localhost but not on the server
//I tested it with Postman
app.get('/id/:number/', (req, res) => {
db_conn.getConnection( (err, conn) => {
if(err) throw err
console.log(`connected as id ${conn.threadId}`)
conn.query("SELECT * FROM _posts WHERE ID=?", [req.params.number], (err, rows) => {
conn.release()
if(!err){
res.send({"table": rows});
}else {
console.log(err);
}
})
})
})
Do you know what could be the reason of that ? Thank you
The solution, add cors.
var cors = require('cors')
app.use(express.urlencoded({extended:true}));
app.use(cors())