Cannot find module './routes/Auth' Require stack: - C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js - mern

I am doing a mern project but at begin I got an error .
const express=require("express");
const mongoose= require("mongoose");
const app=express();
const dotenv=require("dotenv")
dotenv.config()
//connect router
const route=require("./routes/User");
const authRoute=require("./routes/Auth");
mongoose
.connect(
process.env.local
)
.then(()=>console.log("MongoDB connected")).catch((err)=>{
console.log(err)
});
//accept json
app.use(express.json())
app.use("/authData",authRoute)
app.listen(process.env.PORT || 5000,()=>{
console.log("Backend server is running ")
});
the error is
internal/modules/cjs/loader.js:888
throw err;
^
Error: Cannot find module './routes/Auth'
Require stack:
C:\Users\me\Desktop\E-commerce_Web\backendnode\index.js

Related

Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

Cannot read property 'jwtoken' of undefined

here I generate the token at backend in express
..............
router.post("/login",async(req,res)=>{
const {email,password}=req.body;
if(!email || !password){
return res.status(401).send({error:"please filled the data properly"});
}
try {
const loginUser=await User.findOne({email:email});
if(!loginUser){
return res.status(400).send({error:"not found"});
}
const isMatch = await bcrypt.compare(password,loginUser.password);
if(isMatch){
const token=await loginUser.generateToken();
res.cookie("jwtoken",token,{
expires:new Date(Date.now()+15000000),
httpOnly:true,
//secure:true //it is applicable when we use https method
})
console.log(token);
res.send({message:"login success"});
}else{
res.status(400).send({error:"please enter correct data"})
}
} catch (error) {
res.status(400).send(error)
}
})
the token is create when i login in brouser
here is the about page (react)
...................
const verifyPage=async()=>{
try{
const res=await fetch('/about',{
method:"GET",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
credentials:"include"
});
const data=await res.json();
console.log(data);
if(!res.status===200){
const err=new Error(res.error);
throw err;
}
}catch(err) {
console.log(err);
history.push("/login");
}
}
useEffect(()=>{
verifyPage();
},[])
.............
here I verify the token
...........
router.get("/about",Authentication,(req,res)=>{
res.send(req.rootUser);
})
........
The authentication page
............
const jwt = require("jsonwebtoken")
const User=require("../models/shegma")
const Authentication=async (req,res,next)=>{
try{
const token=req.cookies.jwtoken;
console.log(token)
const verifyToken=jwt.verify(token,process.env.TOKENID);
console.log(verifyToken);
const rootUser=await User.findOne({_id:verifyToken._id,"tokens.token":token})
if(!rootUser){throw new Error("user not found")}
req.token=token;
req.rootUser=rootUser;
req.userID=rootUser._id;
next();
}catch(err){
res.status(401).send("no token found");
console.log(err);
}
}
module.exports=Authentication;
..........
here is the error
......
TypeError: Cannot read property 'jwtoken' of undefined
at Authentication (C:\Users\ASUS\Desktop\mern\server\middleware\Authentication.js:6:33)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:47:12)
At first, you need to install cookie-parser inside your server folder
npm i cookie-parser
Then, require cookie-parser inisde that .js file where you have initialized express
const cookieParser = require('cookie-parser')
After this, below const app = express(); just write
app.use(cookieParser())
Here is the full code:-
const express = require('express');
const cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
Do you happen to be parsing the cookies on the incoming request anywhere in your express code?
The req.cookies object being undefined leads me to believe you may not be parsing the request for cookies or that the parsing is not happening before the Authentication handler is called.
For reference: express cookie-parser

Unable to fetch data from workbench Mysql using node js

// import express js
const express = require('express')
// import a body-parser
const bodyparser = require('body-parser');
// executing the express js
const app = express();
// import mysql packages
const mysql = require('mysql');
// use bodyparser in express
app.use(bodyparser.json);
// create an connection details for mysql database
var mysqlConnection = mysql.createConnection(
{
host:'localhost',
user:'root',
password:'keerthi#abitech',
database:'employeedb'
}
)
// To connect with mysql database
mysqlConnection.connect((err)=>{
if(!err)
console.log('DB is connected')
else
console.log('DB connection is failed \n Error: ' + JSON.stringify(err, undefined, 2));
});
// establish an data fetch from database
app.get('/employees', (res, req)=>{
mysqlConnection.query('SELECT * FROM employee', (err, results)=>{
if(err) throw err;
console.log(results);
res.send("post is send")
})
});
// creating an server
app.listen(3000, ()=>console.log("server is running in port number 3000"));
This is my code. I am not able to fetch an data from mysql workbench.
The page is loading only does not give any response.
If i pass the link in postman it shows like this
Could Not Get Any Response
You are currently not sending your data back to the endpoint. Assuming that your connection is successful, you should res.send(results) instead of res.send("post is send") in order to send your results to the /employees endpoint.
Hope this fixes your problem.

How to resolve 502 Mysql query error on Netlify (Express server)

I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);

Express - MySQL conn.end() is not functioning (Cannot enqueue after invoking quit)

I have already read the post Node Mysql Cannot Enqueue a query after calling quit, the conn.end() is in my query block.
My issue is that conn.end in my dashboard.js does not work and breaks the app with the following error.
I need to use it because MySQL connections are flooding the system till Database stop accepting more of them since they all stay open each time that are used.
For this post I will use only one (dashboard.js) of the several routes of my NodeJS application.
`Event.js` is not a part of my working files, probably is a file from `./node_modules`
|events.js:183
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Quit after invoking quit.
at Protocol._validateEnqueue (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:204:16)
at Protocol._enqueue (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:139:13)
at Protocol.quit (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:92:23)
at Connection.end (E:\NodeJS\Project-Change\node_modules\mysql\lib\Connection.js:249:18)
at ServerResponse.res.end (E:\NodeJS\Project-Change\node_modules\express-myconnection\lib\express-myconnection.js:114:54)
at ServerResponse.send (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:191:8)
at fn (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:896:10)
at View.exports.renderFile [as engine] (E:\NodeJS\Project-Change\node_modules\ejs\lib\ejs.js:323:3)
at View.render (E:\NodeJS\Project-Change\node_modules\express\lib\view.js:76:8)
at Function.app.render (E:\NodeJS\Project-Change\node_modules\express\lib\application.js:527:10)
at ServerResponse.res.render (E:\NodeJS\Project-Change\node_modules\express\lib\response.js:900:7)
at Query._callback (E:\NodeJS\Project-Change\routes\dashboard.js:39:17)
at Query.Sequence.end (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
at Query._handleFinalResultPacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
at Query.EofPacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
at Protocol._parsePacket (E:\NodeJS\Project-Change\node_modules\mysql\lib\protocol\Protocol.js:279:23)
app.js (only relative lines)
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
app = express(),
expressValidator = require('express-validator'),
session = require('express-session'),
passport = require('passport'),
flash = require('connect-flash'),
passportConfig = require('./config/passport'),
dbConfig = require('./config/db');
// skipping code about static files, bodyparser, expressValidator, session, passport
passportConfig(passport)
/*MySQL connection*/
var connection = require('express-myconnection'),
mysql = require('mysql');
app.use(
connection(mysql, dbConfig,'request')
);
var dashboard = require('./routes/dashboard.js'); // in this route I apply conn.end()
var router = require('./routes/rates.js');
// skipping app.post/app.get code for /login & /logout & isLoggedIn middleware
app.use('/', router);
app.use('/', dashboard); // issue on that
app.get('/',function(req,res){
res.render('./dashboard.ejs'); //issue on that
});
module.exports = app;
routes/dashboard.js (route)
var express = require('express');
var router = express.Router();
var dashboard = express.Router();
dashboard.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
var dashboard = router.route('/');
//show the CRUD interface | GET
dashboard.get(function(req,res,next){
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query('SELECT SUM(total_price) AS transactions_total FROM transactions WHERE date_created = CURDATE(); SELECT SUM(total_profit) AS total_profit FROM transactions', function(err,rows){
if(err){
console.log(err);
return next("MySQL error, check your query");
}
var ab = {data:rows[0]};
var total_profit = {data:rows[1]};
res.render('dashboard',{ab, total_profit});
conn.end(); // causes the described error
});
// conn.end(); even tried here
});
});
dashboard.all(function(req,res,next){
console.log("route for dashboard executed");
console.log(req.params);
next();
});
module.exports = router;
console.log('dashboard.js loaded!');
config/db.js
module.exports = {
host : 'localhost',
user : 'root',
password : '',
database : 'mydb',
multipleStatements: true,
debug : false
}
config/passport.js
External presentation in case is needed here