Next.js with express.js: Why is app.use not working? - javascript

So I'm working with next.js and a custom server (express.js). I have some middlewares, (f.ex. const attachUser) which I'd like to use in my API endpoints. But for some reason, I am unable to use app.use.
The following code only works, when I don't use app.use(attachUser) and add attachUser to every endpoint manually.
require("dotenv").config();
const express = require("express");
const next = require("next");
const bodyParser = require("body-parser");
const cors = require("cors");
//next.js configuration
const dev = process.env.NODE_DEV !== "production";
const nextApp = next({
dev
});
const port = 3000;
const handle = nextApp.getRequestHandler();
nextApp.prepare().then(() => {
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cors());
const attachUser = (req, res, next) => {
const token = req.cookies["token"];
if (!token) {
return res.status(401).json({
message: "Authentication invalid"
});
}
const decodedToken = jwtDecode(token);
if (!decodedToken) {
return res.status(401).json({
message: "There was a problem authorizing the request",
});
} else {
req.user = decodedToken;
next();
}
};
//app.use(attachUser)
app.get(
"/api/savedItems",
attachUser, //delete when app.use(attachUser) is used
async(req, res) => {
try {
//logic
return res.json(itemData);
} catch (err) {
return res.status(400).json({
error: err
});
}
});
Can someone tell me what I'm doing wrong?
Btw, this is my first project. Any suggestions to improve code are appreciated! Thanks a lot!

You can't write code between a "try {}" and a "catch{}" and aditionally a useless ";" after "try{}". You can use a JS lint tool for checking code

Related

NodeJs Rest api: I can make calls in postman but the route returns as not found in url

When I make a post request to the /login endpoint in postman it works fine and returns all the information. However when I try to navigate to the end point in the url the route returns unfound. In the console I get GET http://localhost:5000/login 404 (Not Found). Why is the console returning for a get request? If I try to call the post request in axios I get xhr.js:177 POST http://localhost:3000/login 404 (Not Found).
app.js
require("dotenv").config();
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const router = express.Router();
const cors = require('cors');
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
const mongoose = require('mongoose');
const connection = "password"
mongoose.connect(connection, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
const clientRoutes = require('./routes/clientRoutes');
const traderRoutes = require('./routes/traderRoutes');
const loginRoute = require('./routes/loginRoute')
app.use('/', clientRoutes, traderRoutes, loginRoute);
// setup a friendly greeting for the root route
app.get('/', (req, res) => {
res.json({
message: 'Welcome to the REST API for Pave!',
});
});
// send 404 if no other route matched
app.use((req, res) => {
res.status(404).json({
message: 'Route Not Found',
});
});
// setup a global error handler
app.use((err, req, res, next) => {
if (enableGlobalErrorLogging) {
console.error(`Global error handler: ${JSON.stringify(err.stack)}`);
}
res.status(err.status || 500).json({
message: err.message,
error: {},
});
});
app.listen(5000, () => console.log('Listening on port 5000!'))
loginRoute.js
require("dotenv").config();
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcryptjs = require("bcryptjs");
const Client = require("../models/clientSchema");
const Trader = require("../models/traderSchema");
function asyncHandler(callback) {
return async (req, res, next) => {
try {
await callback(req, res, next);
} catch (error) {
next(error);
console.log(error);
}
};
}
router.post('/login', asyncHandler(async (req, res, next) => {
let user = req.body;
const trader = await Trader.findOne({ emailAddress: req.body.emailAddress })
if (user && trader) {
console.log(trader)
let traderAuthenticated = await bcryptjs.compareSync(user.password, trader.password);
console.log(traderAuthenticated)
if (traderAuthenticated) {
console.log('Trader match')
const accessToken = jwt.sign(trader.toJSON(), process.env.ACCESS_TOKEN_SECRET)
res.location('/trader');
res.json({
trader: trader,
accessToken: accessToken
}).end();
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
} else if (user && !trader) {
const client = await Client.findOne({emailAddress: req.body.emailAddress})
console.log(client)
let clientAuthenticated = await bcryptjs.compareSync(user.password, client.password);
console.log(clientAuthenticated)
if (clientAuthenticated) {
console.log('Client match')
const accessToken = jwt.sign(client.toJSON(), process.env.ACCESS_TOKEN_SECRET)
res.location('/client');
res.json({
client: client,
accessToken: accessToken
});
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
} else {
res.status(403).send({ error: 'Login failed: Please try again'}).end();
}
})
);
module.exports = router;
You set POSTMAN to make a POST request, right? When you enter a url in the browser, that causes a GET request - and you have no route to manage this that I can see, but for the default Not found.
you are calling with axios with wrong port no. it should, POST method http://localhost:5000/login as your application is running on port 5000.
but you are calling, POST http://localhost:3000/login

TypeError: Cannot read property 'findAll' of undefined - Node.js + Postgresql

I have this problem when I try to get the data from the database
TypeError: Cannot read property 'findAll' of undefined
I made the web using react and node.js + postgresql. Postgres is in our server so I'm not using a localhost. I tried some other post but anything works.
Server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
require("./routes/noticias.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
controller.js
const db = require("../config/db.config");
const noticias = db.noticias;
// Retrieve all noticias from the database.
const getNews = (req, res) => {
noticias
.findAll({})
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || "Some error occurred.",
});
});
};
module.exports = {
getNews,
};
Router
module.exports = (app) => {
const noticias = require("../controllers/noticias.controller.js");
var router = require("express").Router();
router.get("/", noticias.getNews);
app.use("/noticias", router);
};
Thanks for the help ^^
I don't know much about about knex. As far as I know from docs there is a select function not findAll in knex.
Docs: https://knexjs.org/#Builder-select
Please try following method and see what happens
// below line is not required;
// const noticias = datab.noticias;
// Retrieve all noticias from the database.
const getNews = (req, res) => {
datab
.select("column_name_1", "column_name_2", "...")
.from("noticias")
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || "Some error occurred.",
});
});
};
PS: the findAll function is available in sequelize not knex.
Use db.select('*').from('users') to findAll

DialogFlow: How do you handle a NodeJS server with multiple routes?

I am creating a project in DialogFlow and NodeJS where I want to call my fulfillments with a webhook.
In my NodeJS server, I have multiple routes for different functions/intents. For example, /getWeather calls a weather API to return a response about the weather in a specific city. Or /getMovie calls an API to return information about a movie.
DialogFlow only allows for one webhook API, so my question is, how can I call a generic API "/" where it can handle all the different routes and call the correct route when it needs to?
I can use the inline editor on DialogFlow to call each API with the correct route; however, I want to use a single webhook rather than using the firebase functions to call the correct intents.
I can't seem to find example of this online where multiple routes are handled with a generic route.
Image of my Code Stack
index.js:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
server.post
app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose= require('mongoose');
const issuesRoutes = require('./API/Routes/issues');
const movieRoute = require('./API/Routes/getmovie');
const resolvedtaskroute = require('./API/Routes/resolvedtask');
const newtaskRoute = require('./API/Routes/newtask');
mongoose.connect('link', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header('Acces-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
//routes to handle requests
app.use('/issues', issuesRoutes);
app.use('/newtask', newtaskRoute);
app.use('/resolvedtask', resolvedtaskroute);
app.use('/getmovie', movieRoute);
//error handling
app.use((req, res, next) => {
const error = new Error('Not Found');
error.status = 404;
next(error);
})
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
})
})
module.exports = app;
Example of one of my routes: getMovie.js
const express = require('express');
const router = express.Router();
const http = require('http');
router.post('/', (req, res, next) => {
const movieToSearch = req.body.queryResult.parameters.movie;
const API_KEY = 'XXXXX';
const reqUrl = `http://www.omdbapi.com/?t=${movieToSearch}&apikey=${API_KEY}`
http.get(
reqUrl,
responseFromAPI => {
let completeResponse = ''
responseFromAPI.on('data', chunk => {
completeResponse += chunk
})
responseFromAPI.on('end', () => {
const movie = JSON.parse(completeResponse)
let dataToSend = movieToSearch
dataToSend = `${movie.Title} was released in the year ${movie.Year}. It is directed by ${
movie.Director
} and stars ${movie.Actors}.
}`
return res.json({
fulfillmentText: dataToSend,
source: 'getmovie'
})
})
},
error => {
return res.json({
fulfillmentText: 'Could not get results at this time',
source: 'getmovie'
})
}
)
})
module.exports = router;
It is very clear that Dialogflow allows one webhook POST url where every call for intents are made. IF you want to use different API services inside then You should define a webhook and inside the webhook just call the functions which are related to intents using intentMAP. On each function call the external API and return the response back to dialogflow. I will describe a bit more about it using dialogflow-fulfillment.
first thing you need is a webhook POST route for handling dialogflow requests and responses and inside it you need to map intents to its specific function as like:
const { WebhookClient } = require("dialogflow-fulfillment");
const movieService= require("your function for movie API");
router.post("/", async (req, res, next) => {
const agent = new WebhookClient({ request: req, response: res });
const movie = new movieService(agent);
let intentMap = new Map();
intentMap.set("Movie Intent", () => {
//make an api call inside this function
return movie.getinfo();
});
if (agent.intent) {
agent.handleRequest(intentMap);
}
});
Now create another file for external API calls which will be like
async getMovie(){
// get all required paramters from dialogflow here and call APIS and return back response using
agent.add("The info about movie is");
}

Request failed with status code 413, request entity too large

I have a node.js server combined with a react.js frontend. I've a form that requires users to upload files to a AWS S3 bucket. I'm using Multer.js to handle the file upload. I've set the default upload size to a max of 10mb. While there is absolutely no problem in uploading files as long as the file size below 10mb when testing using localhost. However, when I try to do the same from my Nginx Web Server, I get a '413 Error : Request entity too large' while trying to upload anything that is above 1mb. I've tried to follow the solutions here and here but to no luck.
I don't any error output except the 413 Error that my frontend app catches.
Here's the code to my express loader ( referencing this because I've tried the solutions mentioned above on these lines of code. )
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const helmet = require("helmet");
const cors = require("cors");
const morgan = require("morgan");
const path = require("path");
const appRoot = require("app-root-path");
const loadRoutes = require("../api");
const logger = require("./logger");
const { userRoles } = require("../utils/consts");
const authService = require("../services/AuthService");
const expressLoader = (app) => {
app.use(cors());
app.use(express.static(path.join(appRoot.path, "public", "users")));
//app.use(express.static(path.join(appRoot.path, "public", "admin")));
// ATTACH IP ADDRESS TO EACH REQUEST
app.use((req, res, next) => {
req.ipAddress = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
return next();
});
// Extract token from header
app.use((req, res, next) => {
const token = req.headers["authorization"] ? req.header("authorization").split(" ")[1] : null;
if (token) {
req.token = token;
}
return next();
});
// Verify token
app.use(async (req, res, next) => {
if (req.token) {
const decode = await authService.verifyAuthToken(req.token);
console.log(decode);
if (!decode.tokenValid) {
logger.error(`[INVALID JWT ${req.path}] ip: ${req.ipAddress}`);
logger.error(decode.err);
req.isAuth = false;
return next();
} else {
req.isAuth = true;
req.decode = decode.data;
return next();
}
}
return next();
});
// Check if is admin
app.use((req, res, next) => {
const roleId = req.decode ? req.decode.role_id : null;
if (req.isAuth && (roleId === userRoles.SYSOP || roleId === userRoles.ADMIN)) {
req.isAdmin = true;
return next();
}
return next();
});
app.use(morgan("combined", { stream: logger.stream }));
app.use(helmet());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
//app.use(cookieParser(process.env.SCOOK_SECRET));
// app.enable("trust proxy"); TO BE ENABLED FOR NGINX
// LOAD API
app.use(process.env.API_PREFIX, loadRoutes());
// app.use("/admin", (req, res, next) => {
// logger.info(`[ADMIN ROUTE ACCESSED FROM ${ req.ip }]`);
// return res.sendFile(path.join(appRoot.path + "/public/admin/index.html"));
// });
app.get("*", (req, res, next) => {
return res.sendFile(path.join(appRoot.path + "/public/users/index.html"));
});
}
module.exports = expressLoader;
Any help would be appreciated, thank you!

Router not firing .find or .findByID in express app. Using nextjs as well

I am using a NextJS/MERN stack. My NextJS is using my server.js file, along with importing the routes for my API. The routes appear to be working as they do show activity when firing an API call from Postman or the browser. However, this is where the activity stops. It's not getting passed the Model.find() function as far as I can tell. I am not sure if this has to do with Next js and the prepare method in the server.js, or if this is related to the bodyparser issue.
Here is my server.js
const express = require("express");
const urlObject = require('./baseURL')
const passport = require("./nextexpress/config/passport-setup");
const passportSetup = require("./nextexpress/config/passport-setup");
const session = require("express-session");
const authRoutes = require("./nextexpress/routes/auth-routes");
const KBRoutes = require("./nextexpress/routes/kb-routes");
const userRoutes = require('./nextexpress/routes/user-routes')
const pollRoutes = require('./nextexpress/routes/poll-routes')
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser"); // parse cookie header
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextapp = next({ dev })
const handle = nextapp.getRequestHandler()
const bodyParser = require('body-parser');
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/kb', { useNewUrlParser: true });
mongoose.connect('mongodb://localhost:27017/kb')
console.log(process.env.MONGODB_URI)
const connection = mongoose.connection;
const baseURL = urlObject.baseURL
const PORT = process.env.PORT || 3000
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
})
nextapp.prepare().then(() => {
const app = express();
console.log(process.env.PORT, '----port here ----')
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/auth", authRoutes);
app.use("/api/kb", KBRoutes);
app.use('/api/user', userRoutes)
app.use('/api/poll', pollRoutes)
app.get('/posts/:id', (req, res) => {
return nextapp.render(req, res, '/article', { id: req.params.id })
})
app.get('/redirect/:id', (req, res) => {
return nextapp.render(req, res, '/redirect')
})
app.all('*', (req, res) => {
return handle(req, res)
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
// connect react to nodejs express server
And the relevant route:
KBRoutes.get('/', (req, res) => {
console.log(KB.Model)
KB.find({}, (err, photos) => {
res.json(kbs)
})
})
I am able to get to each one of the routes. Before this was working, when I had the NextJS React portion split into a separate domain therefore separate server.js files. Once I introduced NextJs thats when this problem arose. Any help would be greatly appreciated.
It looks like the relevant route is trying to return json(kbs), but kbs doesn't seem to be defined. Returning the result of your find query would make more sense to me, including a nice error catcher and some status for good practice. Catching errors should tell you what's going wrong, i would expect an error in your console anyway that would help us out finding the answer even more.
KB.find({}, (err, photos) => {
if (err) res.status(401).send(err)
res.status(200).json(photos)
})

Categories

Resources