I have a route defined in my server.js file like:
app.use('/file', require('./server/routes/file.js'));
On the top of the file.js
var express = require('express');
var router = express.Router();
var outsideHelper = require('./outsideHelper');
...
router.post('/file', async function(req, res, next){
//Code
var connection = await dbFunc.dbConnect(sqlPool);
var result = await outsideHelper.DoStuff(res, connection);
})
module.exports = router;
outsideHelper works fine, and is exported in that file via
module.exports = {
DoStuff: async function(res, connection){
try {
var localSiteRes = await localFileFunction(res, connection);
return localSiteRes;
}catch(err){
return false;
}
}
The network only shows one request to the file.js however when outsideHelper.DoStuff function is used inside this request router.post('/file... the request gets ran twice, server side. When I remove the outsideHelper function from this however, it only runs once.
Everything works just fine, except on the first attempt after starting my local server.
I do not have a route defined for outsideHelper.js in my server.js because it is not an externally called route, it gets required within the file.js file.
localFileFunction uses JSFTP
Still kinda new to node.js and express.
Thanks in advance
Related
Create an api in router folder to display information about something and display in express using get request in server.js out of the router folder.
api.js in router folder:
function getMessage() {
console.log('Hello my name something')
}
getMessage()
server.js out of router folder::
const express = require("express")
const path = require('path');
const app = express();
const apiHandler = require('./routes/api')
app.use(express.static(path.join(__dirname, 'routes')));
app.get('/none', apiHandler)
})
app.listen(3000, function () {
console.log('Listening');
})
It gives error::
Route.get() requires a callback function but got a [object Object]
I'm completely new to this so anyone can please make me understand how can I display simple message through route folder creating api and display in server.js file.
In the api.js you need to export your function using module.exports like this,
function getMessage(req, res, next) {
res.send('Hello my name something');
}
module.exports = getMessage;
Hope this helps!
Probably a silly mistake but I cannot see why I'm not getting a response from a GET request.
This is part of my server file located in the root:
//server.js
...
var serverRoutes = require('./server/routes');
app.use('/server', serverRoutes);
...
and my routes file:
//server/routes/index.js
var express = require('express');
var router = express.Router();
module.exports = function() {
router.get('/test', function(req, res, next){
console.log("HIT");
res.status(200).send("OK");
});
return router;
}
Everytime I navigate to /server/test in my browser it just stalls. Nothing is logged in the terminal and no "OK" response is received in the browser - what am I missing?
Your serverRoutes module exports a function that returns a router. You need to invoke it in order to pass the Router instance it returns to app.use:
app.use('/server', serverRoutes());
Otherwise, express is going to treat your exported function as a middleware, which will cause the app to hang since it does nothing with the response passed to it.
I am new to NodeJS. So I am writing NodeJS application with socket.io.
I understand how to separate controllers. In my app I created:
controllers/userCtrl.js
controller/marketCtrl.js etc.
And in userCtrl.js controller I did like this:
exports.create = function(req, res) {
// Create user
}
// Other actions
In application I use it:
// ...
var userCtrl = require('./controllers/userCtrl');
app.post('/user', userCtrl.create);
// ...
With models the same. But I have a lot of socket.io related code in app.js and don't understand how remove it (like controllers) from app.js:
var frontend = io.of('/frontend');
frontend.on('connection', function (client) {
logger.info('Someone connected to frontend socket');
client.on('join', function (message) {
logger.info('In join event');
var token = message.token;
if (!token) {
logger.debug('No usertoken provided. Sending login required');
client.emit('join', {error: 103, message: 'Login required', data: null});
return;
}
//... etc..
My question is: How to split socket.io related code into files? What is best practice for it? Thank you!
Different files is still the way. Use exports or module.exports and then just require in your app.js.
Perhaps make a setup() function that takes in an app/http instance, or whatever else you need in your socket.io stuff, and then call that function at the right time in app.js.
-- socketSetup.js --
'use strict';
var io = require('socket.io');
function setup( app, logger, whatever ){
//do stuff here
}
module.exports = setup;
-- app.js --
'use strict';
var express = require('express');
var socketSetup = require('./socketSetup.js');
var app = express();
//other express things
//setup the socket stuff
socketSetup( app, logger );
The result is a shorter and more readable app.js file, and your socket setup is contained as well. Repeat as things grow in your socketSetup.js file as well.
I'm making a nodeJS module, and I want to use expressJS as a framework for it.
I'm trying to see, how I could go by, including a function inside and app.get(); and call it via another file, such as the actual app.
var express = require("express");
var app = express();
app.get("/", function (req, res) {
exports.type = function (text) {
console.log(req.ip);
console.log(text);
}
});
now when I use this, and i call it on the actual app like:
var web = require("directory_to_file");
var express = require("express");
var app = express();
var http = require("http").Server(app);
app.get("/", function (req, res) {
web.type("Hello, world");
});
http.listen(10022, function () {
console.log("server is up");
});
I get an error:
TypeError: Property 'type' of object #<Object> is not a function
anyone know a way to make it so I can call the function?
There are generally two things you want to export as a module - an API and a Middleware. The classic example of middleware is an authentication module. To do the middleware, just export the middleware. I tend to do a little more than that so I can configure the middleware later. Something along the lines of this:
module.exports = exports = function(config) {
// Do something with config here
return function(req, res, next) {
// your middleware here
};
};
You can then use your middleware in your main program like this:
var app = require('express')(),
mymodule = require('./mymodule');
var config = {}; // replace with whatever config you need
app.use(mymodule(config));
app.listen(process.env.PORT || 3000);
To implement an API, you will create a Router object, then attach your routes to the Router object. You can then "mount" your router in your main program. For example, you could have a file called 'myroutes.js' with the following contents:
var express = require('express'),
myroutes = express.Router();
myroutes.get('/foo', (req, res) => {
res.status(200).type('application/json').send({ myparam: 'foo' });
});
module.exports = exports = myroutes;
Have the following in your main program:
var app = require('express')(),
myroutes = require('./myroutes');
app.use('/api', require('./myroutes'));
app.listen(process.env.PORT || 3000);
Here, in 'myroutes.js', I'm defining a sub-route of /foo and then in the main program, I'm mounting that on /api - so I would access /api/foo to access that API.
In your directory_to_file you are only exporting on app.get('/') which will never be called.
You could add in your directory_to_file the following code
var express = require('express');
var router = express.Router();
router.get('/', function(req, server) {
console.log(req.ip);
});
module.exports = router;
And in your main file you could use app.use('/', web)
A short explanation:
You are creating a new express app / config in your directory_to_file file which won't be launched or used. So your app.get event won't be fired once.
That's why web.type is not a function. You are not exporting anything.
Use the way I provided. This is a commonly used method.
You could call the code I provided a "route". Create multiple routes / route files and include them in your main method.
Your code just looks confused. If I understand you correctly, what you are really trying to do (at least in Node/express terminology) is write your own middleware.
Express is designed with this in mind and it's pretty straightforward e.g.
ipLogger.js
module.exports = function(req, res, next) {
console.log(req.ip);
next();
}
app.js
var http = require("http")
, express = require("express");
, app = express()
, server = http.Server(app)
, ipLogger = require("./ipLogger.js");
app.use(ipLogger()); // log IP of all requests
// handle routes
server.listen(10022, function() {
console.log("server is up");
});
I have https server written in express js. And I added domains to my server. App.js file:
var d = require('domain').create();
d.on('error', function(error) {
console.error("Domain caught error: "+ error.stack);
});
d.run(function() {
var express = require('express');
var appServer = express();
var https = require('https').createServer(options, appServer);
https.listen(8000, function() {
log.info('Server is listening on port ' + 8000);
});
appServer.use(appServer.router);
var routes = require('./routes')(appServer); //my routes file
});
I have route handler functions in other files. How can I use domain created in my app.js file in my route files without exporting it from app.js file.
Update:
routes.js file:
var auth = require('./auth');
module.exports = function(app) {
app.namespace('/login', function(){
app.post('/user', auth.verifyUser);
});
};
auth.js file:
exports.verifyUser = function(req,res) {
//here I want to see my domain
};
You can pass it when you require your routes:
var routes = require('./routes')(appServer, d);
Then within your routes/index.js file:
module.exports = function(app, domain) {
// ...
};
Update
To update the answer based on the question update, here's a possible solution to include the domain within each route definition. There are a couple ways to do this (you could make each route a class, which would be instantiated and passed the domain, then have a function defined per route, for example). Because the intent is to keep these route definition signatures function(req, res) as you've defined above for verifyUser, we're going to need to pass the domain to this route prior to calling the function. Keeping this very simple, we can do just that with a setDomain function:
Same code in your main index.js when you require your routes:
var routes = require('./routes')(appServer, d);
In your routes.js, you can pass the domain to the routes via the setDomain function:
var auth = require('./auth');
module.exports = function(app, domain) {
auth.setDomain(domain);
app.namespace('/login', function() {
app.post('/user', auth.verifyUser);
});
};
Finally, in your auth.js file, you can get the domain, and have access to it within the scope of the file to use it in the verifyUser function:
var myDomain;
module.exports.setDomain = function(domain) {
myDomain = domain;
};
module.exports.verifyUser = function(req, res) {
res.send("myDomain: " + myDomain);
};
I'm not sure I really like this solution, but again, it's keeping the signature the same for verifyUser. Maybe you'll think of a better one, or want to refactor your code to better make use of this domain you're passing around within your code (maybe define it somewhere else and pull it from there wherever it's needed).