I am building a rest api with node.js and mysql. But in my GET I am getting a error of "could not get any response" with router.get that uses the mysql.
Here is my code, mt it helps.
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
res.locals.connection.connect();
next();
});
user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
In that user.js if i use a get without using the mysql the connection works.
You need to understand JavaScript nature(Asynchronous programming) and you must not open mysql connection in each request, you can use connection pooling and keep connection open, just acquire connection and release it after query.
updated app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
const mysql = require('mysql');
//Database connection
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
app.use(function(req, res, next){
pool.getConnection(function(err, connection) {
res.locals.connection = connection;
next(err);
});
});
updated user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
res.locals.connection.release();
if (error) throw error;
//res.json({"status": 200, "error": null, "response": results});
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
Related
I’m new to node.js and just tried to follow some tutorial. But I get nothing after I sent this GET request.
I used following code.
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createConnection({
user: "root",
host:"localhost",
password:"",
database:"userdb",
});
app.use(express.json());
app.get("/users", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
res.json(result);
});
});
app.listen(3001, () => console.log('Listening on port 3001...'));
Could anyone please help me with this?
strong textI'm trying to create my first CRUD with Mysql, Node js and Express.js following a tutorial.
The problem is, in the video this code works, but in my visual give the error aboyt getConnection is not a function.
If anyones can help, I'll apreciate.
Server.js
const express = require("express");
const mysql = require("mysql");
const myconn = require("express-myconnection");
const routes = require("./routes");
const app = express();
const serverPort = process.env.PORT || 9000;
const dbOptions = {
host: "localhost",
user: "3306",
password: "123456",
database: "catalog",
};
//server running
app.listen(serverPort, () => {
console.log(`App listening at ${serverPort}`);
});
//routes
app.get("/", (req, res) => {
res.send("welcome to my API");
});
app.use("/phones", routes);
Routes.js
const express = require("express");
const routes = express.Router();
const myconn = require("express-myconnection");
routes.get("/", (req, res) => {
req.getConnection((err, conn) => {
if (err) return res.send(err);
conn.query("SELECT * FROM phones", (err, rows) => {
if (err) return res.send(err);
res.json(rows);
});
});
});
module.exports = routes;
UPDATE : solved.
IT WAS A POINT after catalog and I didn't write the port correctly!!!!!
I am creating a simple server application using the following code
const express = require('express');
const mysql = require('mysql');
const PORT = process.env.PORT || 3000;
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'mydata',
});
connection.connect(function (err) {
err ? console.log(err) : console.log(connection);
});
require('./routes/html-routes')(app);
app.listen(PORT, () => {
console.log('app running on port %s', PORT);
});
module.exports = app;
in file server.js
and then a route in file html-routes.js
const mysql = require('mysql');
module.exports = function (app) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
to get data from database
I get the error
ReferenceError: connection is not defined
at /Users/arjunbhandari/Desktop/GL-IT/backend/routes/html-routes.js:5:5
I have struggled for the past 6 hours and cannot understand the problem.
Thanks
As the error states, there is no connection defined (or inherited) within ./routes/html-routes.js.
You still can pass the connection property as a second argument to your exported function:
const mysql = require('mysql');
module.exports = function (app, connection) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
then update the route mounting call within your main server file:
require('./routes/html-routes')(app, connection);
You should review your route implementation logic as this should not be the best design approach to use data-store connections.
i'm using ExpressJS as server, and MySql as local db.
I need to get some data from a table and send the query result to a vanilla JS file or just edit HTML trought NodeJS, but i don't know how...
My Express server:
const express = require("express");
const app = express();
const path = require("path");
app.use(express.static("../public"));
app.get("/home", function(req, res) {
res.sendFile(path.join(__dirname + "/../index.html"));
});
1- To query from your database tables, you'll need to use a Node.js MySQL client or an ORM, I use mysql in the following example:
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
2- Write your query and send back the results to the end-user
const express = require('express');
const router = express.Router();
router.get('/home', function(req, res, next) {
connection.query('SELECT * FROM `tablename`;', function (error, results, fields) {
if (error) throw error;
res.send({ results });
});
});
You have to choose a template engine like pug
You should connect to your database as mentioned before :
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
and make your query form your TableName :
const express = require('express');
const router = express.Router();
router.get('/home', function(req, res, next) {
connection.query('SELECT * FROM `tablename`;', function (error, results, fields) {
if (error) throw error;
res.render('index', { 'data' : results })
});
});
And for your template page :
ul
each val, index in data
li= index + ': ' + val
I'm trying to display all members from MYSQL database with Node Js. But I get some errors. My database name is apibase and I have table members (id, name, email, phone) My code is below:
//routes.js file
const pool = require('../data/config');
const router = app => {
app.get('/', (request, response) => {
response.send({
message: 'Welcome to the Node.js Express REST API!'
});
});
// Display all users
app.get('/members', (request, response) => {
pool.query('SELECT * FROM members', (error, result) => {
if (error) throw error;
response.send(result);
});
});
// Display a single user by ID
app.get('/members/:id', (request, response) => {
const id = request.params.id;
pool.query('SELECT * FROM members WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
}
module.exports = router;
And my database.js file:
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: '',
database: 'apibase',
};
const pool = mysql.createPool(config);
module.exports = pool;
And app.js file
const express = require('express');
const port = 8080;
const bodyParser = require('body-parser');
const routes = require('./routes/routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
routes(app);
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
I don't know what is the problem with this code, can somebody help me with this.