Restify middleware like express middleware specifying route - javascript

I need to use restify middleware system just like express middleware, but it doesn't seem to work since restify needs only a callback when using
server.use(callback)
Express allows us to make something like :
server.use(patternConcerned, callback)
So, when the request will match the patternConcerned, the server will execute the middleware call.
Does it exist something similar using restify ?

No, Restify do not allow the creation of sub-application.
You're code doesn't work because Restify server.use(callback) instantiate a new middleware on your entire application while Express server.use(patternConcerned, callback) instantiate a new middleware on a sub-application.

Related

TypeError: require(...).listen is not a function ERROR

I am trying to execute a .js file and is giving me the following error
The piece of code that is apparently giving me problems is
var io = require('socket.io').listen(app);
Can someone tell what the problem is? I have very little experience with Javascript and Node.js :/
This whole thing is a bit confusing because socket.io supports all sorts of ways of initializing it and there are variations depending upon whether you want to hook up to an existing http(s) server or have it create its own server.
If you just want a socket.io server by itself, you would do this:
const io = require('socket.io')();
This uses the socket.io Server factory function and passes it default options (which assumes port 80).
If you want an http server that you can both use with Express and with socket.io, you would do this:
// create http server and start it
const app = require('express')();
const server = app.listen();
// create socket.io server and bind it to an existing http server
const io = require('socket.io')(server);
Or this:
// create Express listener instance
const app = require('express')();
// create http server and bind the Express listener instance to it
const server = http.createServer(app);
// create socket.io server and bind it to the existing http server
const io = require('socket.io')(server);
// start the http server
server.listen();
Both of these use the socket.io Server factory function and pass it an existing http server object that it will share and hook up to.
Or (this syntax not used very often), if you want to more deliberately create a stand-alone socket.io server instance yourself:
// Load socket.io Server class from socket.io module
const { Server } = require("socket.io");
// create socket.io server instance
const io = new Server();
// start socket.io server
io.listen();
Your code is not working for a couple reasons:
require('socket.io') returns a Server factory function that doesn't have a .listen() method. You need a server instance to get a .listen() method.
You don't pass app to a socket.io instance. You pass app to an http server instance when you create that server with http.createServer() or you hook them together automatically with app.listen() which creates the http server for you in that .listen() method.
FYI, the socket.io .listen() method on a socket.io Server instance can either accept a port number (which defaults to 80 if not passed) or it can accept an existing, already created http server instance. The Server class factory function which is what require('socket.io') returns will also accept those two types of arguments as illustrated above.
FYI, I assumed you're using Express because of your use of the app variable. If that's not the case, then please show the rest of the code that shows what app is and where it comes from.

What is this express variable is doing?

I recently started learning JS and I am a basic programming background previously but always stuck on OOPs concepts.
So here we are importing I think the express module by writing the required (express). But I don't understand why we are storing this in a variable.
Likewise then storing express() in app variable then using app variable to do some stuff.
I mean how's this is working? What is What in this code block? Please explain in detail.
Thanks in advance.
const express = require('express')
const { createReadStream } = require('fs')
const app = express()
app.get('/' , (req,res) => {
createReadStream('index.html').pipe(res)
})
Line 1: You import the express node module that you installed with npm i express and store it in a constant (const).
Line 2: You import the function or variable createReadStream from the file system module of node.js (fs module) and make it available for use in this file.
Line 3 you assign the express() function from the express module above to a constant called app, so you now have everything express related available to you on the app constant.
Line 4-5: You use the get method from the express() function you have stored in the app constant, and create a route for the base url of your app / (e.g. domain.com/ or localhost:8000/). If you request something from the server you send a GET request. If you send some data use POST or PUT, for example, the express() function in app have these methods for you to use, too (app.post for example).
When Postman or a regular user with a browser hits this part of your domain (route) with a GET request, the arrow function on line 4 (req, res) => kicks in. It takes in the request (req) and the result (res) parameters so you can use those inside of the function if you wish. On the req parameter you have available whatever is in the body the user sends in from a form, for example. In your case your route streams back a html file to the user via http in order to display it in the user's browser.

Is Express.js platform-independent?

I'm just starting out with Express.js. In the official getting started guide, they showed the following basic code:
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
The first parameter to app.get() is a forward-slash indicating the root directory. But the slash is a backward-slash in windows systems. Does express deal with these differences automatically, or do we need to write extra code for it? When I was using the http module, I did have to consider and correct for these differences. Thanks for the help!
app.get('/', ...) declares a handler for when an HTTP GET request is made to the URL path /. E.g. http://localhost:8080/. It has nothing to do with file paths on the server’s file system. If you use any functions that do take a file path, you may have to account for the differences between Windows and *NIX, that depends on the function.

What is the purpose of this? var http = require('http')

I'm super new to server-side, so apologies for such a basic question.
I was looking at an example of a Node/Express server file in this blog post and came across this:
var http = require('http')
What is the purpose of requiring 'http'? It doesn't seem to be any kind of dependency. Is this something from Express/Node? Could someone please explain?
'http' is a core module in node.js.
Node.js needs to create http/https servers, hence we have to import the http module in order to create an HTTP Server.
Thus,
var http = require('http')
is just to import the built-in http module, so that we can create http server which will respond to our requests. After importing the module, a server can be created by using the createServer() method offered by http module.
var server = http.createServer(handleRequest);
For more detailed info, visit https://nodejs.org/api/http.html
You’ll use Node’s require function to use the http module. require is similar to keywords like import or include in other languages. require takes the name of a package as a string argument and returns a package. There’s nothing special about the object that’s returned—it’s often an object, but it could be a function or a string or a number.
var http = require('http')
Node has a built-in module called http. It is useful for building web applications. and by using the above code you are getting all things those are exposed by http module.
It's like creating object of a class and getting access of all the properties(Variable and Functions)of that class.
To use the HTTP server and client one must require('http').
It is an API provided by Node.js. If you want to know more on this, https://nodejs.org/api/http.html
It doesn't seem to be any kind of dependency
But it is. Further down in the example there's this line:
var server = http.createServer(app).listen(port, function() { ...
which requires http to work. You probably missed it.

What is the express.js equivalent of the node.js http module's "req.url"?

When using vanilla node.js' http.createServer, you can get the url that the client requested with req.url.
When using express.js, the code for responding to a HTTP GET request is something like:
app.get('/', function (req, res) {
res.send('Hello World!')
})
My problem with this is that it requires you to have an individual app.get for every single page or item on the server. How do I use express.js like the vanilla node.js server to deal with each get request within the callback generated by the http.createServer?
Hi
To answer the specific question (as outlined in your title), ExpressJS provides
req.originalURL which is equivalent to Node's req.url
req.baseUrl which is actually the path that was mounted by Express
So, essentially, Express' req.baseUrl + req.url is equivalent to Node's req.url
Also, Express' routing DOES NOT require you to explicitly set the path to each page; it also accepts regex strings with which you can process specific requests.
Take a look at Express' routing; it should be of immense benefit to you.
Register you followup handler like an express module...
app.use(function(req, res, next){ ... YOUR CODE HERE ... })
Do this after your routes...
You shouldn't ever have a need to use req.url. Express allows you to have variables in your routes.
app.get('/article/:id', function(req, res) {
// req.params.id will be whatever came after /article/
});
You can also get fancy and use a regular expression.
app.get(/\/article(\d+)/, function(req, res) {
// req.params[0] will have the digits of /article123
});
If you really want the URL, req.url still exists. However, you should use routes to handle all your routing logic. I've never really had the need to use req.url.

Categories