{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false} - mysql

I am new to MySQL, and I am having difficulties in getting my data from MySQL database.
import express from 'express';
import mysql from 'mysql';
const app = express();
const db = mysql.createConnection({
host:"localhost",
user:"root",
password:"2000",
database: "test"
})
app.get('/', (req, res) => {
res.json('hello this is backend')
})
app.get('/books', (req, res) => {
const q = "SELECT * FROM books"
db.query(q, (err, data) => {
if(err) {
return res.json(err)
}
else{
return res.json(data)
}
})
})
app.listen(8800, () => {
console.log('Connected to backend server...');
});
as it gives following error on localhost:8800/books/
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
any help would be valuable :)

Related

How can I separate an API into diferent files? (routes) Node.js + MySQL

I'm new here. I wanted to know how can I "separate" mi app.js (API) into several files, mainly for the routes but also the connections too if it is posible. I tried several video tutorials but none of them worked, so here is my code (only file), I want the routes in a separated file (routes.js):
const mysql = require('mysql')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3050
const app = express()
app.use(bodyParser.json())
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'shop'
})
app.get('/', (req, res) => {
res.send('Welcome to my API!')
})
//ROUTES!!!
app.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
app.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
connection.connect(error => {
if (error) throw error
console.log('Database server running!')
})
app.listen(PORT, () => console.log(`Server running on ${PORT}`))
You can use express.Router object to define some routes in separe file. Then export the router object and do app.use('/api/some-sub-path', router)
You can read more about Router here https://expressjs.com/en/guide/routing.html
Also I advice you to read this article https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf
create n new file ApiRouter.js and add following code in it.
const express = require("express");
const router = express.Router();
router.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
router.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
module.exports = router;
//now go to app.js file and add these line of codes below
app.use(bodyParser.json())
const route = require('./path/ApiRouter.js'); // require from file
app.use('/', route);
Create router in another file by:
const router = require('express').Router;
router.get();
And now in app.js use router as
app.use('/' , router);

TypeError: req.getConnection is not a function

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 getting PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR

I am not able to connect to MYSQL with nodejs even though I can access MySQL with Workbench. I am getting the PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR error and I am not able to determine anything wrong with the code here. How should I go about it? Many thanks in advance.
const express = require('express')
const cors = require('cors')
const mysql = require('mysql')
const app = express()
const SELECT_ALL_PRODUCT_QUERY = 'SELECT * FROM products';
const connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'password',
database:'reactdb'
})
app.use(cors())
app.get('/', (req, res) => {
res.send('hello world from the product server')
})
app.get('/productlist', (req, res) => {
connection.query(SELECT_ALL_PRODUCT_QUERY, (err, results) => {
if(err){
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
})
app.listen(4000, () => {
console.log('Product server is listening to port 4000')
})
I managed to solve the connection error by creating a new MySQL user instead of using the root user. Thanks

how can i post data from reactjs form to mysql database

How can I send this data to database MySQL from a reactjs form? I'm a beginner in reactjs and I'm tired of trying.
In the back-end I use nodejs, express, and cors, so if u can tell me how because I have to finish this work.
The console returns GET Localhost 404 Not Found.
This is what I do but I don't know there is a better way to make it.
import React, { Component } from 'react'
import { Table,Button,
Modal,ModalHeader,
ModalBody,ModalFooter,
Label,Input,Form } from 'reactstrap';
export default class Db1 extends Component {
state = {
users: [],
newUserData: {
nom: '',
prenom: '',
adresse: '',
email: ''
},
newUserModal:false,
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
fetch('http://localhost:4000/users')
.then(response => response.json())
.then(response => this.setState({ users: response.data}))
.catch(err => console.error(err))
}
addUser = () => {
let { nom,prenom,adresse,email } = this.state.newUserData;
fetch(`http://localhost:4000/users/add?
nom=${nom}&prenom=${prenom}&adresse=${adresse}&email=${email}`,{
method: 'POST',
body: JSON.stringify({
nom: this.nom,
prenom: this.prenom,
adresse: this.adresse,
email: this.email
}),
headers: {"Content-Type": "application/json"}
})
.then(this.getUsers)
.catch(err => console.error(err))
this.setState({newUserModal:false});
console.log(this.newUserData) // return undefined
}
toggleNewUserModal = () => {
this.setState({
newUserModal: ! this.state.newUserModal
});
}
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbusers',
});
connection.connect(err => {
if (err) {
console.log("conection error");
return err;
}
});
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the users server')
});
// Selectionner Tous Les Utilisateurs
app.get('/users', (req, res) => {
const selectQuery = 'SELECT * FROM userslist';
connection.query(selectQuery, (err, results) => {
if(err) {
res.send(err)
}
else {
res.json({data: results})
}
});
});
// Ajouter Un Nouveau Utilisateur
app.post('/users/add', (req, res) => {
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let insertQuery ="INSERT INTO userslist SET ?"
const user={nom,adresse,prenom,email}
connection.query(insertQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Editer Un Nouveau Utilisateur
app.post('/users/update/:id', (req, res) => {
let id = req.params.id;
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let updateQuery =`UPDATE userslist SET ? WHERE id=${id}`
const user={nom,adresse,prenom,email}
connection.query(updateQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Suprimer un Utilisateur
app.post("/users/delete/:id", (req, res) => {
let id = req.params.id;
let sql = 'DELETE FROM userslist WHERE id=?';
connection.query(sql, [id], (error, results, fields) => {
if (error)
console.error(error.message);
console.log("Deleted Row(s):", results.affectedRows);
res.json({error:false,data: results})
});
});
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});

How to create a webservice using node.js to insert data into mysql?

I've a table in mysql that i need to be populated by calling a webservice.
The catch is, I would like to pass the data to be inserted into the database as parameters to the webservice.
How would I do this?
Using the MySQL module
http://npmjs.com/mysql
const mysql = require('mysql');
const express = require('express');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db'
});
connection.connect();
app.get('/', (req, res) => {
connection.query(`SELECT * FROM table`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});
app.post('/update/user/:id?', (req, res) => {
const id = req.params.id;
const username = req.body.username;
connection.query(`UPDATE MyGuests SET username='${username}' WHERE id=${id}`, (error, data) => {
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});