Express JS REST API with MySQL - javascript

I am doing an exercise with Express.js and MySQL. At the moment I have 4 files. The error is,
TypeError: areas.getAreas is not a function
at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/--/--/--/src/app.js:10:20)
at Module._compile (module.js:653:30)
But I am sure I am declaring the variable and function so, I don't understand why is it happening.
I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object.
The main file is, app.js and it contains:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
connection(mysql);
userRoutes(app);
app.listen(app.get('port'), ()=> {
console.log('server on port 3000');
});
The next files are:
connection.js
'use strict';
module.exports = function connection(mysql){
mysql.createConnection({
host: 'http://x.x.x.x',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxx'
})
};
areas.js
'use strict';
let areasModel = {};
areasModel.getAreas = (callback) => {
if(connection) {
connection.query(
"SELECT * FROM areas",
(err, rows) => {
if(err) {
throw err;
}
else {
callback(null, rows);
}
}
);
}
};
module.exports = areasModel;
userRoutes.js
'use strict';
const areas = require('../models/areas');
module.exports = function (app) {
app.get("/", (req,res)=>{
areas.getAreas((err, data) => {
res.json([]);
});
});
}

try importing connection.js in areas.js,
maybe because never enter in that if statement, returns undefined

Related

Deploying Express app to Vercel gives errors

Running the server locally produces no problems, however when I deploy to Vercel I get the following error:
TypeError: Cannot read properties of undefined (reading 'startsWith') at connectionStringHasValidScheme (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:9:30) at new ConnectionString (/var/task/server/node_modules/mongodb-connection-string-url/lib/index.js:85:34) at parseOptions (/var/task/server/node_modules/mongodb/lib/connection_string.js:201:17) at new MongoClient (/var/task/server/node_modules/mongodb/lib/mongo_client.js:46:63) at Object.<anonymous> (/var/task/server/db/conn.js:3:16) at Module._compile (node:internal/modules/cjs/loader:1159:14) at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) at Module.load (node:internal/modules/cjs/loader:1037:32) at Module._load (node:internal/modules/cjs/loader:878:12) at Module.require (node:internal/modules/cjs/loader:1061:19)
I'm really not sure what the problem is - I've done a bit of googling but it hasn't produced many results for this issue (at least not that I found).
server.js
const express = require("express");
const app = express();
const cors = require("cors");
const bp = require('body-parser');
require("dotenv").config({ path: "./db/config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/auth"));
app.use(require("./routes/user"));
const dbo = require("./db/conn");
app.listen(port, () => {
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("preview");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I tried cutting the code down to a minimal just to figure out what component is causing the bug, unfortunately with no result.
When you deploy your app to Vercel, you also need declare your environment variables in your project settings page.
Go to the Environment Variables page of your Project Settings and define ATLAS_URI value. Note that you need to deploy your project again before new environment variables becomes available.

TypeError('app.use() requires a middleware function')

enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.

Facing problems while using HBS

I am a total noob in Backend and I am learning Express and using HBS as template engine.
This happens to me every time while using hbs partials in Express.
Code
const express = require("express");
const app = express();
const hbs = require("hbs");
const path = require("path");
const port = process.env.PORT || 3000;
// public static path
const static_path = path.join(__dirname, "../public");
const templates_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("views", templates_path);
hbs.registerPartial(partials_path);
app.use(express.static(static_path));
// routing
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/weather", (req, res) => {
res.render("weather");
});
app.get("*", (req, res) => {
res.status(404).render("404error");
});
app.listen(port, () => {
console.log("listning on port " + port);
});
Error
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
^
Error: Attempting to register a partial called "D:\Projects\ExpressWeb\templates\partials" as undefined
at HandlebarsEnvironment.registerPartial (D:\Projects\ExpressWeb\node_modules\handlebars\dist\cjs\handlebars\base.js:80:15)
at Instance.registerPartial (D:\Projects\ExpressWeb\node_modules\hbs\lib\hbs.js:222:35)
at Object.<anonymous> (D:\Projects\ExpressWeb\src\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
description: undefined,
fileName: undefined,
lineNumber: undefined,
endLineNumber: undefined,
number: undefined
}
Adding this to increase the discripting because Stack Overflow is not letting me post this because i am uplaoding more code than discription and i dont know what to ask more.
According to the docs it is - hbs.registerPartials(partials_path);
not hbs.registerPartial(partials_path);

passport.use is not a function

I am trying to add passport service to my app , but I am getting the following error,
I have already installed all the dependencies and tried searching for this error but got none , please Help
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
TypeError: passport.use is not a function
at module.exports (/home/udit/Goserv/app/config/passport.js:11:14)
at Object.<anonymous> (/home/udit/Goserv/app/server/server.js:9:45)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
Here is the passport.js file:
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
var User = require('../model/user.js');
var config = require('../config/database');
module.exports = function(passport){
var opts = {};
opts.secretOrKey = config.secret;
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
User.find({id: jwt_payload.id}, function(err, user){
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
})
}));
}
you will get this error if import it like this
import * as passport from 'passport';
should be
import passport from 'passport';
You need to require passport.js from your app.js file with the following command:
require('./config/passport')(passport);
All the passport-related commands in your app.js file should be:
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);

Node.js file server on Rpi3 Jesse

I have a file server that works perfectly on my Rpi 2 with Raspian and I have been trying to migrate it to a newer Rpi3 with Jesse. Every time I try to run it I get the following error stack
/media/pi/DemoServer.js:82
server.listen(port, () => {
^
SyntaxError: Unexpected token )
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Any suggestions on why this is occurring? Is there a subtle nuance between the two distributions that I should address?
Here is the code for the server (with some omissions).
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const util = require('util');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 1001;
const dirToServe = '/media/pi/Shared';
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
server.post('/media/pi/Shared', function(req,res) {
});
//Serve the static folder and the index of the folder
server.use('/', serveIndex(dirToServe, { icond: true }));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders }));
server.listen(port, () => {
console.log('listening on port ' + port);
});

Categories

Resources