Last active
November 26, 2019 00:47
-
-
Save cyb3rsalih/d73bdc3abefdd7e835f376e98bf44373 to your computer and use it in GitHub Desktop.
mysql connection with nodejs. Use url path as parameter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //REF: https://dev.to/saulojoab/how-to-get-data-from-an-mysql-database-in-react-native-53a4 | |
| const express = require("express"); | |
| const bodyParser = require("body-parser"); | |
| const mysql = require("mysql"); | |
| const connection = mysql.createPool({ | |
| host: "localhost", // Your connection adress (localhost). | |
| port: 8889, // 3309 , 8888, 8080 .... | |
| user: "user", // Your database's username. | |
| password: "password", // Your database's password. | |
| database: "db", // Your database's name. | |
| queueLimit: 0, // unlimited queueing | |
| connectionLimit: 0, // unlimited connection, | |
| socketPath: "/../mysql/mysql.sock" // IMPORTANT | |
| }); | |
| // Starting our app. | |
| const app = express(); | |
| app.use("/", function(req, res) { | |
| // Connecting to the database. | |
| let route = req.url.split("/")[1]; | |
| connection.getConnection(function(err, connection) { | |
| if (!err) { | |
| // Executing the MySQL query (select all data from the 'users' table). | |
| connection.query("SELECT 1+1 AS " + route, function( | |
| error, | |
| results, | |
| fields | |
| ) { | |
| // If some error occurs, we throw an error. | |
| if (error) throw error; | |
| // Getting the 'response' from the database and sending it to our route. This is were the data is. | |
| res.send(results); | |
| }); | |
| } else { | |
| console.log(err); | |
| } | |
| }); | |
| }); | |
| // Starting our server. | |
| app.listen(3000, () => { | |
| console.log("Go to http://localhost:3000/users so you can see the data."); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment