I have an example
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('hello world');
});
In the runtime (for example in 10 sec), I want to stop handling my / endpoint, so when I will make a request, the response would be like Cannot GET /
How can I achieve this behaviour?
You need to create a flag that can be set based on when you want to keep preventing the route from providing the data. Instead of showing Cannot GET /, you should send the status code 503 status code i.e service unavailable.
var express = require('express');
var app = express();
app.get('/', function (req, res) {
if (flag) {
res.status(503).send('Service Unavailable');
} else {
res.send('hello world');
}
});
This could be great if you want to make it for a single route. When you want to control many routes, you can create middleware and use flag similar to the above one.
Related
I'm trying to make a chat app using node.js as backend, where every client has a specific IP so I need to get the IP of the client using my api.
You can use a middleware express-ip
const express = require('express');
const app = express();
const expressIp = require('express-ip');
app.use(expressIp().getIpInfoMiddleware);
app.get('/', function (req, res) {
console.log(req.ipInfo);
});
you can get the variable from req object req.connection.remoteAddress
app.get('/', function (req, res) {
console.log(req.connection.remoteAddress);
});
I'm completely new to server development and NodeJS, so my apologies if this question sounds stupid or if such a question already exists.
I was following a simple NodeJS tutorial and building a simple "Hello World" server. I noticed that http.createServer took only one function as its argument.
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
I tried passing another function to it like the following:
var http = require('http');
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type':'text/html'});
res.end("Hello World");
},
function (req, res) {
res.write("Blahblah");
res.end();
}
).listen(8080);
But hitting localhost:8080 returned only Hello World.
So I was wondering if I could pass multiple functions to it and if not, then why.
Thank you for your time
You cannot pass multiple functions. If you want multiple listeners for incoming requests, you can just register another listener for incoming requests:
const server = http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end("Hello World");
}.listen(8080);
// add additional listener
server.on('request', function(req, res) {
if (req.url === "/goodbye") {
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end("goodbye");
}
});
Note: right from the doc for http.createServer(), it says this about the function parameter passed to http.createServer():
http.createServer([options][, requestListener])
The requestListener is a function which is automatically added to the 'request' event.
Doc for the request event is here.
As others have said, it is pretty rare to use a plain http server like this because some simple routing is nearly always helpful and a lightweight framework like Express offers very useful features without really getting in the way of anything you might want to do. In the case of Express, you'd use code like this:
const express = require('express');
const app = express();
// define handler for /goodbye URL
app.get('/goodbye', function(req, res) {
res.send("goodbye");
});
// define handler for /hello URL
app.get("/hello", function(req, res) {
res.send("hello");
});
const server = app.listen(8080);
Here express, keeps a list of the URLs that you wish to handle and then listens for each incoming request, compares it against the URLs you wanted to handle and calls the appropriate route handler. It has lots of other features for routing too such as middleware, wildcards, parameterized URLs, etc...
I'd recommend you use something like express if you want multiple routes:
const express = require('express');
const app = express();
app.get('/hello', (req, res) => res.send('Hello World!'));
app.get('/world', (req, res) => res.send('Hello World!'));
app.listen(3000, () => console.log('Example app listening on port 3000!'));
Node.js provides you with the features to create your own webserver from scratch, unless you want to create a whole new framework i would recommend using something like expressjs.
Have a look at this following tutorial if you're a newbie and want to create restful services.
Build a RESTful API Using Node and Express 4 | Scotch.io
Its a fairly simple and straightforward tutorial
Node Express documentation gives a hello-world example:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Does the order of listen() and get() matter? (could they be swapped?) And what would happen if get() and listen() were called a second time after the first calls as above?
Let's deconstruct the example :
app.listen(3000)
this line attaches your app to a port, in this case 3000. It enables you to access it by typing http://localhost:3000, you typically would not want to change the port you app runs on durig execution.
app.get('/', function (req, res) {
res.send('Hello World!')
})
this is basically a listener, which will be called when you make a GET request to the / route. It tells your app what to answer when you type the url on your browser.
It is attached to the app object, whether the app is running or not, so it can be written before listen, after, or in another file altogether.
In the strange case where you'd have a second listener on the same route, one of them would not be executed. I suggest you test it yourself if you really want to know which takes precedence, here's a sample code :
app.get('/', function (req, res) {
res.send('Will I be executed?')
});
app.get('/', function (req, res) {
res.send('or maybe I will?')
});
app.listen(3000)
It can be used for
app.get('/', function(req, res){
res.send('hello world');
});
which is to display in browser upon receiving request on Port defined.
What other uses are there of the command app.get?
app.get has two uses.
the first is using it as a route just like you showed,
or even using multiple middlewares additionally to the route like in the following example:
var middleware = function(req, res, next) {
//do something, then call the next() middleware.
next();
}
app.get('/', middleware, function (req, res) {
res.render('template');
});
but app.get can also be used together with app.set:
var appEnv = app.get('env'); //tells you the environment, development or production
var appPort = app.get('port'); //tells you the port the app runs on
console.log('app is running in ' + appEnv + ' environment and on port: ' + appPort);
app.set('any-string', 'any value'); //set custom app level value
var any_string = app.get('any-string'); //retrieve custom app level value
console.log('any_string = ' + any_string);
thats the uses for app.get i found so far,
have fun
jascha
In express app.get or app.post is used to define a route. Both of them work the same way. They accept two parameters
1) A string that defines the path of the route
2) A single or multiple callbacks.
app.get('/', function(req, res){
res.send('hello world');
});
What the above code does is it tells express that when a request is made on / endpoint it executes the code in the callback function. The function that you have defined just sends an html message
However there are lot's of different responses that you can send to the browser. They are enumerated in the guide
I am building an app with express js which will have different clients like web and mobile. I didnt want to use one app for both as some middleware would be additional burden. For say like session middleware. So is it possible for one project to have two apps. And how would it work?
The app object that you make in express is a function(req,res,next) that is suitable for Express's own middleware chains. So you can use app.use to send requests matching a leading path fragment to an app defined elsewhere.
Docs: http://expressjs.com/api.html#app.use
$ npm install express
//mobile.js
var app = require('express')();
app.get('/', function(req, res){
res.send('Mobile Route')
});
module.exports = app;
//desktopApp.js
var http = require('http');
var express = require('express');
var desktopApp = express();
var mobileApp = require('./mobile.js');
desktopApp.use('/mobile', mobileApp)
desktopApp.use(desktopApp.router);
desktopApp.use(express.errorHandler());
desktopApp.get('/', function(req, res){
res.send('Desktop Route')
});
desktopApp.get('/mobile', function(req, res){
// Because Express respects the order that you set up the middleware chain,
// the mobileApp `/mobile` route gets first dibs to send a response or next()
res.send('Inaccessible Desktop Route')
});
desktopApp.get('/mobile/foobar', function(req, res){
// When mobileApp can't find any suitable route matching this path, it gives
// up, and desktopApp continues to pass the request down the middleware stack.
// It ends up matching this route, where we send a response
res.send('Desktop Route')
});
http.createServer(desktopApp).listen(3000, function(){
console.log('Listening on 3000');
});
// Results
$ curl localhost:3000/
Desktop Route
$ curl localhost:3000/mobile/
Mobile Route
See the vhost example on the express github repository.
You can have a "main" app, which routes the requests to one app or another. You should write a middleware to establish the conditions where one app or another are requested. express.vhost is a good example, but maybe you need other checks than the domain one.
main-app.js
(The file called to start the server.)
// load dependencies
var main = express();
main.use( express.vhost( 'mobile', require( './the-mobile-app' ) );
main.use( express.vhost( '*', require( './the-web-app' ) );
main.listen( /*...*/ )
the-mobile-app and the-web-app.js
var app = express();
//
// setup your application conf, middleware, and routes
//
module.exports = app;
I wanted to share a different approach that I used in a project recently:
function renderAppropriate(template1, template2){
return function(req, res){
if(req.session && req.session.mobileOn){
res.render(template1);
} else {
res.render(template2);
}
};
};
app.get('/', function(req, res, next){
// do some stuff
next()
}, renderAppropriate('someMobileTemplate', 'someDesktopTemplate')
);