Is there any way to link two servers in nodejs (expressjs)? - javascript

I have two servers
http://127.0.0.1:7777/
http://127.0.0.1:7778/
I'm trying to link the actions of these two servers.
For example, when I click on server 7778 I create a folder and put an action that detects the file create
var fs = require('fs');
if (fs.existsSync('/home/diegonode/Desktop/ExpressCart-master/New')) {
console.log("hello");
}
but I use an app like this and this command only works when it is included in router get
How can I link the actions of these two servers?
var express = require('express');
var router = express.Router();
var common = require('./common');
// The homepage of the site
router.get('/', function(req, res, next) {
var number_products = req.config.get('application').number_products_index ? req.config.get('application').number_products_index : 8;
req.db.products.find({ product_published: { $in: [ 'true' , 'true2'] }, }).limit(3).exec(function (err, results) {
res.render('index', {
title: 'Shop',
results: results,
session: req.session,
message: clear_session_value(req.session, "message"),
message_type: clear_session_value(req.session, "message_type"),
config: req.config.get('application'),
helpers: req.handlebars.helpers,
page_url: req.config.get('application').base_url,
show_footer: "show_footer"
});
});
});
please help me
I REFER how I can click action (or another type of action) of one server and detect this click in another server
I refer use router get from another server, not from the actual server and get I do a some action
router.get( ('http://127.0.0.1:7778/data '),

Related

Should express router.get intervene page loading?

I have built a mean-stack application. I use http to communicate data between front-end and back-end. For example,
In front-end, I have
app.factory('ops', ['$http', function ($http) {
var o = {};
o.get = function (id) {
return $http.get('/ops/' + id)
.then(function (res) {
return res.data
})
};
return o;
}]);
In the back-end, in routes/index.js, I have
var express = require('express');
var router = express.Router();
... ...
router.get('/ops/:op', function (req, res, next) {
console.log("/ops/:op");
res.json(req.op);
})
module.exports = router;
And it is the job of ui-router to load a page like https://localhost:3000/ops/59202d6a38b09685ff6b0581:
.state('ops', {
url: '/ops/{id}',
...
However, since I turned html5Mode to true, it seems that router.get('/ops/:op', function (req, res, next) { console.log("/ops/:op"); res.json(req.op); }) can directly load the page https://localhost:3000/ops/59202d6a38b09685ff6b0581. If I comment .state('ops' ... and load the page, I see /ops/:op is displayed in the server console, and the content of the json data is shown in the browser. At the same time, in the browser console, I see
Resource interpreted as Document but transferred with MIME type application/json: "https://localhost:3000/ops/59202d6a38b09685ff6b0581"
Could anyone tell me if we should let router.get('/ops/:op' ... intervenue the loading of a page in this way? If not, how could we disable it?
PS: routers/index.js is referenced in app.js as follows:
var index = require('./routes/index');
app.use('/', index);

What events/actions/methods trigger a http Post request?

Consider the following code from an express app:
var express = require('express');
var router = express.Router();
var standupCtrl = require('../controllers/standup.server.controller');
/* GET home page. */
router.get('/', function(req, res) {
return standupCtrl.list(req, res);
});
/* POST filter by member name - home page. */
router.post('/', function(req, res) {
return standupCtrl.filterByMember(req, res);
});
// ............ more code here
module.exports = router;
exports.list = function(req, res) {
var query = Standup.find();
query.sort({ createdOn: 'desc'}).limit(12).exec(function(err, results){
res.render('index', {title: 'Standup - List', notes: results});
});
};
exports.filterByMember = function(req, res) {
var query = Standup.find();
var filter = req.body.memberName;
query.sort({ createdOn: 'desc' });
if (filter.length > 0)
{
query.where({ memberName: filter})
}
query.exec(function(err, results) {
res.render('index', { title: 'Standup - List', notes: results });
});
};
I know that when submitting a form you can specify a
method = get/post
For this scenario (where nothing such has been specified) , how does the server know which to trigger (post or get) when user navigates to '/' (e.g. Homepage)?
More generally, My question is:
What events trigger a Post/Get action (if not explicitly specified) ?
(PS: I know typing anything in the address bar of a browser triggers a GET request)
Thanks a lot in advance!
HTTP GET is pretty much the default everywhere if you don't specify otherwise.
Most POSTs are the result of either a form submit or an explicit call via AJAX or as a web service call (like RPC from another server). You CAN handcraft POST requests using programs like curl, but again that would be rare. In every toolkit I've seen, it's GET by default.
And rarely (VERY), you might find some RPC provider (such as an IoT or other embedded device) that only speaks POSTs (to save on code space).

Node.js API design and route handling

I am not really sure what to title this, but I'm new to Node.js. I just found a neat REST API project on GitHub to implement but I'm not sure how I can split all GET and POST etc. to separate files.
I have one singular api.js file where I have
function API_ROUTER(router, connection, md5) {
var self = this;
self.handleRoutes(router, connection, md5);
}
API_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
router.get("/", function(req, res) {
res.json({"Message" : "Hello World !"});
});
};
module.exports = API_ROUTER;
Now how can I create a sibling other.js and use:
var api = require('./api.js');
// Create router.get, router.post etc. here?
but I'm not sure how I can split all GET and POST etc. to separate files.
One way you can organize your routes would be to have a separate object for each route that has the handlers (separated by HTTP methods) and other needed info such as the path:
api/home.js
module.exports = {
path: '/',
handlers: {
'get': function(req, res) {
res.json({"Message" : "Hello World !"});
},
'post': {
// ...
}
// ...
}
}
api/other.js
module.exports = {
path: '/other',
handlers: {
'get': function(req, res) {
res.json({"Message" : "Other !"});
},
// ...
Then you can load all of these inside the handleRoutes method:
API_ROUTER.prototype.handleRoutes = function(router, connection, md5) {
var routes = ['home', 'other'];
routes.forEach(function(name) {
// load the current route object (NOTE: you should use the path module for determining file path in a cross-platform manner)
var routeObject = require('./' + name + '.js');
var apiPath = routeObject.path;
var handlers = routeObject.handlers;
var methods = Object.keys(handlers);
// assign handlers for each method
methods.forEach(function(method) {
router[method](apiPath, handlers[method]);
});
});
};
This will install all your routes with the appropriate information and handlers.
Now you can call this code by instantiating your API_ROUTER with the necessary data:
// initialize the api (and handle the routes internally)
var Api = new require('./api.js')(router, connection, md5);
If you implement a RESTful API, then you should keep in mind that this is just one way how you can provide data, and you might want to change it in future, as of that the API will most of the time only be a translation layer.
Normally you will split your code based on the resources, and the code that is handling the request won't have so much logic, it will just take the request and pass it to you internal API. For that purpose you not really need an additional layer if you already use express.js or a similar library.
In express the app.use([path,] function [, function...]), already provides the functionality you would need to modularize your code. For each resource your will create an own express.Router that itself also might mount another sub module. So for this part you do not really need a library.
When might a library be useful:
if it automatically translates thrown errors to the correct response codes
if it includes a tool to automatically create a documentation to your API
if it fully abstracts the underlaying routing system so that you can hook into express, hapi, ... without the need to change the code.
Here how a setup with express.js could look like
./lib/rest/customer.js
var customerSystem = require('../customer-system');
var express = require('express');
var router = new express.Router();
router.get('/:id', function(req, res, next) {
customerSystem.find({
id: req.params.id
}, function(err, customer) {
if (err) {
res.status( /*correct status code*/ ).send( /*depending on the api return json, xml, ....*/ )
} else {
res.send( /*depending on the api return json, xml, ....*/ )
}
})
});
router.delete('/:id', function(req, res, next) {
customerSystem.delete({
id: req.params.id
}, function(err) {
//...
});
});
router.post('/', function(req, res, next) {
//...
});
//save the customer id for the pass to the sub routers
router.use('/:id', function(req, res, next) {
req.customerId = req.params.id;
next();
});
router.use('/:id/addresses', require('./customer-address') )
module.exports = router;
./lib/rest/customer-address.js
var customerSystem = require('../customer-system');
var express = require('express');
var router = new express.Router();
router.get('/:id', function(req, res, next) {
customerSystem.find({
id: req.customerId
}, function(err, customer) {
// ...
})
});
/* ..... */
//save the address id for the pass to the sub routers
router.use('/:id', function(req, res, next) {
req.addressId = req.params.id;
next();
});
router.use('/:id/addresses', require('./customer-address') )
module.exports = router;

passport.js doesn't work on sails socket environment

I think passport.js is a amazing framework. Unfortunately, however, it seems to be that doesn't support socket. Why I said this is that Sails framework provides http and socket. When user connected sails's service through passport.js, it doesn't matter. Accessing by socket makes error. Because socket may not support middleware?
Anyway, the critical problem, I don't know how apply passport.js on socket.
Indeed, the websocket requests do not pass threw the passport middleware, but it is possible to use a workaround. Are you using this sails passport generator ?
I added this code to the passport policy to add passport methods to the socket requests.
/** Content not generated BEGIN */
var http = require('http')
, methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
/** Content not generated END */
module.exports = function (req, res, next) {
// Initialize Passport
passport.initialize()(req, res, function () {
// Use the built-in sessions
passport.session()(req, res, function () {
// Make the user available throughout the frontend
res.locals.user = req.user;
/** Content not generated BEGIN */
// Make the passport methods available for websocket requests
if (req.isSocket) {
for (var i = 0; i < methods.length; i++) {
req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
}
}
/** Content not generated END */
next();
});
});
};
Alexis gave the right answer... I think it's the way recommanded by Mike, regarding this message : https://stackoverflow.com/a/17793954/6793876
Just delete passport's mentions in config/http.js , make new policy passportMiddleware.js with the following content :
//passportMiddleware.js
var passport = require('passport');
var http = require('http');
module.exports = function (req, res, next) {
// Initialize Passport
passport.initialize()(req, res, function () {
// Use the built-in sessions
passport.session()(req, res, function () {
res.locals.user = req.user;
var methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
if (req.isSocket) {
for (var i = 0; i < methods.length; i++) {
req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
}
}
next();
});
});
};
And finally add this policy to all controllers, in policies.js :
module.exports.policies = {
RabbitController: {
nurture : ['passportMiddleware','isRabbitMother'],
feed : ['passportMiddleware','isNiceToAnimals', 'hasRabbitFood']
}
};

Express routes: .get() requires callback functions but got a [object Object]

Ok, this should be easy for somebody to point out.
I checked the other similar questions and none helped.
I'm trying to move all my routes to a separate routes.js file. In it I have:
module.exports = function (app) {
var user = {
list : require('./routes/user.js')
}
, index = {
index : require('./routes/index.js')
}
app.get('/', function(request, response){
response.send('You made it to the home page.')
});
app.get('/users', user.list);
}
And in my app.js file I have this:
var register_routes = require('./routes.js')
register_routes(app)
My index route works fine, but it kicks back on app.get('/users', user.list); with this error:
.get() requires callback functions but got a [object Object]
This is an out of the box express app so theres not too much to describe.
Thanks.
EDIT: Per request, here is what is in ./routes/user.js :
exports.list = function(req, res){
res.send("respond with a resource");
};
You export an object with the key list having the your function as value.
So to access your function you would need to do this require('./routes/user.js').list
Or with your code user.list.list.
To solve this you have two possibilities.
Either write:
var user = {
list : require('./routes/user.js').list
}
Or:
module.exports = function(req, res){
res.send("respond with a resource");
};
EDIT
If your routes/user.js will probably later look like this:
module.exports.list = function(req, res){
res.send("respond with a resource");
};
module.exports.delete = function(req, res){
res.send("delete user");
};
If yes then you can just write it that way in your routes.js:
var user = require('./routes/user.js');
I think what you want is:
module.exports = function (app) {
var user = {
list : function(request, response){
require('./routes/user.js');
}
}
}
, index = {
index : function(request, response){
require('./routes/index.js')
}
}
app.get('/', function(request, response){
response.send('You made it to the home page.')
});
app.get('/users', user.list);
}
In this way give a callback to the route and this callback execute the require.
If you are using router in your application for all routing purpose,
var express = require('express');
var router = express.Router();
var index = require('./index');
/* GET home page. */
router.get('/', index.list);
module.exports = router;
then in your index.js file, just do
router.list = function(req, res){
res.send("respond with a resource");
};
After so many time seeking around in web, I found something.
First of all, You instantiate the code like this on another file, (e.g.: humancomms.ts):
import express from 'express';
export function shout(request: express.Request, response: express.Response, next: () => void) {
response.send('Shout so loud!');
}
export function speak(request: express.Request, response: express.Response, next: () => void) {
response.send('Speak less loud!');
}
What exactly this code does? Nobody knows.(Hehe, just kiddin')
This make a middleware functions to separate from main server file to... organize, of course.
And how We can use it? Just like this (inside your server file):
const shout = require('./humancomms').shout;
const speak = require('./humancomms').speak;
app.use('/shout', shout);
app.use('/speak', speak);
This code takes all middlewares funcs and executes when some path is called.
This not solve all problems like multi path to same type, as if You want call differently intensities of shout ('/shout/high?asd=asd', '/shout/low?asd=asd'), but there is a catch You can try on secondary file:
import express from 'express';
export function shout(request: express.Request, response: express.Response, next: () => void) {
if (request.path.includes('/high')) {
response.send('Shout so loud!');
} else if (request.path.includes('/low')) {
response.send('Really shout?');
}
}
Look at this good article about:
TypeScript Express tutorial #1. Middleware, routing, and controllers (https://wanago.io/2018/12/03/typescript-express-tutorial-routing-controllers-middleware/)
and the official documentation website:
Writing middleware for use in Express apps (http://expressjs.com/en/guide/writing-middleware.html)

Categories

Resources