Router creation in API, SP response - javascript

I'm starting to develop an API but I don't have a high level of programming. I am occupying express and node.js. I am trying to add the response of the call to the SQL_SP_STATUS to a Router, in order to get its results after a call:
var connectionStatus = async function (stpName = process.env.SQL_SP_STATUS) {
const response = await sqlDB.getStatus(dbSQL,stpName);
return response;
}
When trying to make the Router from some examples that I have, it does not work, I have set it up as follows:
router.get('/test', async function () {
stpName = process.env.SQL_SP_STATUS;
let connectionStatus = stpName ;
const response = await sqlDB.getStatus(dbSQL,stpName);
return response;
});
The truth is that I do not know the correct way to do it, please I need advice.
Thank you very much in advance, I will be attentive to your answers.
Regards!

It depends on how you want to do it. You can have your routes defined e.g.
testroute.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.json({});
});
module.exports = router;
Have a router file that includes all your routes.
const express = require('express');
const router = express.Router();
router.use('/api/test', require('./routes/testroute'));
module.exports = router;
and maybe in your express file have something like
const express = require('express');
const app = express();
app.use(require('./routes'));
Read the documentation for better understanding.
express documentation

Related

Unable to setup Express server on HTTPS

Trying to set up my Express server on HTTPS but unable to access my api. Here is my code:
// server.js
const express = require('express');
const { readFileSync } = require('fs');
const https = require('https');
const app = express();
const key = readFileSync(
'/etc/letsencrypt/live/mydomain.com/privkey.pem',
'utf8'
);
const cert = readFileSync(
'/etc/letsencrypt/live/mydomain.com/fullchain.pem',
'utf8'
);
const ca = readFileSync(
'/etc/letsencrypt/live/mydomain.com/chain.pem',
'utf8'
);
const credentials = { key, cert, ca };
const port = 443
const server = https.createServer(credentials, app);
server.listen(port, () => console.log(`Server is running on port ${port}`));
The error I am receiving is a 502 Bad gateway on all calls to the server.
Everything worked perfectly before when I was running on HTTP like this:
const server = app.listen(8000, () => {});
Beside the URL on my site I can see the padlock icon and it says my site is secure so I believe my certifcate is valid.
Have seen a lot of similar questions posted on here and followed what I've seen in responses. I've even asked chatGPT to check my code and it doesn't see any errors. I've also tried reading my SSL keys as .env variables so I don't think the issue is an incorrect file path.
Can anybody please help me find the solution?
EDIT
Here is an example of a get request I am making to my backend using axios:
const fetchMembers = async () => {
await axios
.get(`/api/total-users`)
};
This invokes a function totalUsers with express.Router from a users file in my routes folder on the backend:
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/total-users', totalUsers);
const totalUsers = async (req, res) => {
try {
const total = await User.find().estimatedDocumentCount();
res.json(total);
} catch (err) {
console.log(err);
}
};
I am using a middleware app.use with a prefix /api and importing the users file to make a connection to my endpoints:
// server.js
const userRoutes = require('./routes/users')
app.use('/api', userRoutes)
While editing this question I tried modifying the middleware prefix to `:443/api' however this still hasn't helped.
Where is User defined inside of routes/users.js? You need to import your DB models before accessing them like this:
const total = await User.find().estimatedDocumentCount();
Otherwise, generally when running fetch('/api...), React will try to access localhost:3000/api instead of localhost:443/api.
React needs to know where to proxy requests to the backend. One way is using the http-proxy-middleware library and by defining a setupProxy.js file.
client/src/setupProxy.js
/**
* Proxy most calls to the server
* #type {Array}
*/
/* eslint-disable #typescript-eslint/no-var-requires */
const { createProxyMiddleware } = require('http-proxy-middleware');
const proxy_urls = ['/api/*';
const target = 'https://localhost:443';
module.exports = function (app) {
proxy_urls.forEach((url) => {
app.use(url, createProxyMiddleware({ target }));
});
};

node js post 404 not found with router

hello i have a issue i build a project when i start to add the server side
i am using node js express
i create fetch post to spesific url from the database (mongoDB)
and i want to add the users
now
its workd but i try to reconfigure the files and using router and now i get 404 when i try to make the post is upload some code
just need to know where is the bad request
the url i want to fetch is
http://localhost:5000/shopping-cart/user/sign-up
Axios.post("http://localhost:5000/shopping-cart/user/sign-up", user).then((response) => {
console.log(response);
});
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path")
const productRouter = require("./routes/product.route");
const userRouter = require("./routes/user.route");
const { setServerConfiguration } = require("./config");
setServerConfiguration(app);
mongoose.connect('mongodb://localhost/shopping-cart-data-base');
app.use("/shopping-cart", productRouter);
app.use("/user/sign-up", userRouter);
app.listen(5000);
const router = require('express').Router();
const errorsHandler = require('../utils/errorsHandler');
const UserModel = require('../models/User');
router.post("/user/sign-up", async (req, res) => {
let body = req.body;
console.log(body)
try{
await UserModel.create({
name: body.name,
username: body.username,
password: body.password,
shoppingHistory: [],
});
res.send(body);
}catch(e){
return errorsHandler(e, req, res);
}
});
module.exports = router;
Your router is mounted on the /user/sign-up prefix:
app.use("/user/sign-up", userRouter);
Which means that all requests that start with /user/sign-up will get passed to your router.
Your router should be routing relative to that prefix, so to make it work, use this:
router.post('/', ...)
Try this url
"http://localhost:5000/user/sign-up"
If you want to use "http://localhost:5000/shopping-cart/user/sign-up" than you need to define route like that, for example:
router.post("shopping-cart/user/sign-up", async (req, res) => {
//Your code
})
404 route not found
app.use("/shopping-cart", productRouter) => route1
app.use("/user/sign-up", userRouter); => route2
route1 other route2
url http://localhost:5000/shopping-cart request route1
url http://localhost:5000/user/sign-up request route2

How to call modules.export route as an api?

Greeting to everyone !! i have done something but i think i have done it wrong when its time for APIs
I have set my node js code for some routes like this
const admin_Controllers = require('./adminControllers/controllers')
// using the admin controller from the file
admin_Controllers(app)
Like i am sending app as a parameter to the file and there i am coding like this
module.exports = (app) => {
app.get('/viewall', (req, res) => {
res.send("Hello i am stuck here")
});
}
Now the issue is which path should i use to access this get request.
You should use the path which you have define for that specific middleware.
http://hostname:[port_number]/viewall
You can declare your function like this:
module.exports = {
app(req,res){
res.send("Hello i am stuck here")
}
}
And you call using express.Router(), like:
const express = require('express');
const routes = express.Router();
const admin_Controllers = require('./adminControllers/controllers');
routes.get('/viewall', admin_Controllers.app);

How to use nested middleware in express.js

I want to make a change from the actual structure of my code. This is the actual code i have:
//index.js
var routes = require('./routes');
var subdomain = require('express-subdomain');
//require express app with settings
var app = require('./app');
//export the application
module.exports = app;
// routes request like endusers-api.mydomain.ext/
app.use(subdomain('endusers-api', routes.apis.endusers));
// routes request like mydomain.ext/
app.use(routes.webapps.endusers);
//routes/index.js
var apis = {endusers: require("./apis/endusers")}
var webapps = {endusers: require("./webapps/endusers")}
var routes = {apis: apis, webapps: webapps}
module.exports = routes;
//routes/apis/endusers
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-api-access"), function(req, res, next) {
res.json({
"name" : "Endusers API"
});
});
module.exports = route;
//routes/webapps/endusers.js
var express = require('express');
var route = express.Router();
var logger = require('../../lib/logger');
route.get('/', logger("endusers-webapp-access"), function(req, res, next) {
res.render('endusers/index', {title: 'Homepage'});
});
module.exports = route;
Now I want to change the above code to this (feel free to tell me if this is a good approach of doing things in Node.js or not):
//index.js
var middlewares = require('./middlewares');
var app = require('./app');
module.exports = app;
//i want to change to this
app.use(middlewares.endusersApi);
app.use(middlewares.endusersWebapp);
//Stuff for creating server and listening...
//middlewares/index.js
var middlewares = {
endusersApi : require("./apis/endusers"),
endusersWebapp : require("./webapps/endusers")
}
module.exports = middlewares;
//middlewares/apis/endusers.js
//TODO
//middlewares/webapps/endusers
//TODO
How should I write the TODO portions above. It look like we will need nested middlewares (a middleware calling another middleware). Please, your suggestions.
I found the answer using by express.Router().all() method.
//middlewares/apis/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/',subdomain('endusers-api', routes.apis.endusers));
//the two next lines are alternatives to the line above
//middleware = subdomain('endusers-api', routes.apis.endusers); //can assign only one route
//middleware.use(subdomain('endusers-api', routes.apis.endusers)); // can use many routes
module.exports = middleware;
//middlewares/webapps/endusers.js
var routes = require('../../routes');
var express = require('express');
var middleware = express.Router();
middleware.all('/', routes.webapps.endusers);
//the two next lines are alternatives to the line above
//middleware = routes.webapps.endusers; //can assign only one route
//middleware.use(routes.webapps.endusers); // can use many routes
module.exports = middleware;

Add Routes at Runtime (ExpressJs)

I would like to add routes at run time. I read that its possible but I am not so sure how. Currently I using the following code:
var app = express();
function CreateRoute(route){
app.use(route, require('./routes/customchat.js'));
}
And customchat looks like
var express = require('express');
var router = express.Router();
router.route('/').get(function (req, res) {
var url = req.baseUrl;
var roomname = url.substring(url.lastIndexOf('_') + 1);
res.render('chat', { name: roomname , year: new Date().getFullYear().toString()});
});
module.exports = router;
When I call the method CreateRoute before I start listening it will link the route. But when I do it at runtime it wont create a new route.
My goal is to add routes add runtime. I will generate an path like /room_Date. And this should be added at runtime using the template customchat.
I am using express version 4.13.
Thanks in advance for your help.
customchat.js should called customChat.js and be
const customChat = (req, res) => {
const { name } = req.params;
const year = new Date().getFullYear().toString();
res.render('chat', { name , year });
}
module.exports = customChat
then when you create your app
const express = require('express')
const customChat = require('./routes/customChat.js')
const app = express()
app.use('/chat/:name', customChat)
See the official Express routing docs for more information.

Categories