Issue
I have built an Express Server like this:
var mysql = require('mysql2');
var express = require('express');
var app = express();
var PORT = 3000;
app.get('/getDataFromDatabase', function(req, res) {
console.log("Called")
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "", // Password is filled ()
database: "casesdb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM cases", function (err, result, fields) {
if (err) throw err;
res.status(200).send(result);
console.log("Test")
});
});
});
app.listen(PORT, () =>
console.log(`Example app listening on port ${PORT}!`),
);
My Goal is to call the /getDataFromDatabase in client javascript and then use that data. How would I go about that?
Solution
Try the following on client-side:
<script>
fetch('http://localhost:3000/getDataFromDatabase')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
</script>
Answered By – Saif Ali Khan
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0