Express Js Router methods - node.js

I am new to expressjs and nodejs .I have found few methods in express router using visual studio code vs intellisense .For few of them i didn't found any documentation regarding below methods ,how exactly it can be used in real world like get,post,put,patch .So i thought to ask in stackoverflow.It might help everyone who are looking similar to this
const router = express.Router()
router.options
router.head
router.checkout
router.connect
router.copy
router.lock
router.merge
router.mkactivity
router.mkcol
router.move
router.'m-search'
router.notify
router.propfind
router.proppatch
router.purge
router.report
router.search
router.subscribe
router.trace
router.unlock
router.unsubscribe
router.apply
router.bind
router.arguments
router.caller
router.call

Please see: https://expressjs.com/en/api.html#routing-methods
Express Routing methods
Express supports the following routing methods corresponding to the HTTP methods of the same names:
checkout copy delete get head lock merge mkactivity mkcol move m-search notify options patch post purge put report search subscribe trace unlock unsubscribe
The API documentation has explicit entries only for the most popular HTTP methods app.get(), app.post(), app.put(), and app.delete(). However, the other methods listed above work in exactly the same way.

Related

fastify-swagger is not picking up my dynamic routes

I've been a fan of ExpressJs for a long time but in a Youtube video I stumble upon Fastify and wanted to give it a try
I'm struggling in making the fastify-swagger plugin work as I assume it should work - dynamic setup to pick up the schema from each route, but I'm certainly missing something ๐Ÿ˜”
here's my test repo that after running, none of my routes appear
my setup for the plugin is the default one
but all I see is
I've read in the read me that because of OpenAPI specs, some properties, like description are mandatory or will not pick up the route, but I've added in one route, and still does not pick up, I've also added tags wondering if that was also mandatory, but nothing...
does anyone know what am I missing? must be a simple thing, but got me puzzled this last few days ๐Ÿ˜”
I ran into the same issue and ended up solving it by following the first Usage example line-by-line: https://github.com/fastify/fastify-swagger#usage
const fastify = require('fastify')()
(async () => {
// set up swagger
await fastify.register(require('#fastify/swagger'), {
...swagger config
});
// define all your routes
// then call these
await fastify.ready()
fastify.swagger()
})();
Consider the order in which your plugins are loaded, the routes need to be registered before fastify swagger. If fastify swagger comes first, it doesn't detect any route.
I encountered this issue in my project. In my case, I solved it using fastify-plugin. Looking at the source code for fastify-swagger, it seems to rely on a hook listening for onRoute events to detect routes. I'm thinking maybe encapsulation can interfere with the plugin's ability to receive the events.

Express.js POST request returns 404 [duplicate]

Despite knowing JavaScript quite well, I'm confused what exactly these three projects in Node.js ecosystem do. Is it something like Rails' Rack? Can someone please explain?
[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]
I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:
Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.
Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.
Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.
Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.
Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static (a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static is the same as connect.static. (Both were known as staticProvider until recently.)
My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.
The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).
What Node.js comes with
http / https createServer which simply takes a callback(req,res) e.g.
var server = http.createServer(function (request, response) {
// respond
response.write('hello client!');
response.end();
});
server.listen(3000);
What connect adds
Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework
The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect(); you get a function app that can:
Can handle a request and return a response. This is because you basically get this function
Has a member function .use (source) to manage plugins (that comes from here because of this simple line of code).
Because of 1.) you can do the following :
var app = connect();
// Register with http
http.createServer(app)
.listen(3000);
Combine with 2.) and you get:
var connect = require('connect');
// Create a connect dispatcher
var app = connect()
// register a middleware
.use(function (req, res, next) { next(); });
// Register with http
http.createServer(app)
.listen(3000);
Connect provides a utility function to register itself with http so that you don't need to make the call to http.createServer(app). Its called listen and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen. From source
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, you can do:
var connect = require('connect');
// Create a connect dispatcher and register with http
var app = connect()
.listen(3000);
console.log('server running on port 3000');
It's still your good old http.createServer with a plugin framework on top.
What ExpressJS adds
ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:
Can be registered with createServer like connect since it too is just a function that can take a req/res pair (source).
A use function to register middleware.
A utility listen function to register itself with http
In addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.
Has view engine support.
Has top level verbs (get/post etc.) for its router.
Has application settings support.
The middleware is shared
The use function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.
Which one should you use?
My opinion: you are informed enough ^based on above^ to make your own choice.
Use http.createServer if you are creating something like connect / expressjs from scratch.
Use connect if you are authoring middleware, testing protocols etc. since it is a nice abstraction on top of http.createServer
Use ExpressJS if you are authoring websites.
Most people should just use ExpressJS.
What's wrong about the accepted answer
These might have been true as some point in time, but wrong now:
that inherits an extended version of http.Server
Wrong. It doesn't extend it and as you have seen ... uses it
Express does to Connect what Connect does to the http module
Express 4.0 doesn't even depend on connect. see the current package.json dependencies section
node.js
Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.
node.js as a web server: express
Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.
Middleware and Connect
Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:
logger request logger with custom format support
csrf Cross-site request forgery protection
compress Gzip compression middleware
basicAuth basic http authentication
bodyParser extensible request body parser
json application/json parser
urlencoded application/x-www-form-urlencoded parser
multipart multipart/form-data parser
timeout request timeouts
cookieParser cookie parser
session session management support with bundled MemoryStore
cookieSession cookie-based session support
methodOverride faux HTTP method support
responseTime calculates response-time and exposes via X-Response-Time
staticCache memory cache layer for the static() middleware
static streaming static file server supporting Range and more
directory directory listing middleware
vhost virtual host sub-domain mapping middleware
favicon efficient favicon server (with default icon)
limit limit the bytesize of request bodies
query automatic querystring parser, populating req.query
errorHandler flexible error handler
Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.
What to do?
Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see.
Now you are in.
Connect offers a "higher level" APIs for common HTTP server functionality like session management, authentication, logging and more. Express is built on top of Connect with advanced (Sinatra like) functionality.
Node.js itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.
Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.
Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.
middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and response..how request,response,express server sit in express app
in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way.
how middleware sit between request and response small chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made..
all middle ware can access request object,response object and next function of request response cycle..
this is good example for explaining middleware in express youtube video for middleware
The stupid simple answer
Connect and Express are web servers for nodejs. Unlike Apache and IIS, they can both use the same modules, referred to as "middleware".

Make request data available from different places

We are building a middleware with apollo-server, express, and nodejs.
There is some info in the HTTP request headers that weโ€™ll like to be available from different places down the call stack without the need to be passing them as parameters or touching each resolver, some kind of java thread-local.
We have a solution using async_hooks, but in some cases, it doesnโ€™t work, we tried AsyncLocalStorage with no success, so we are looking for alternatives.
Apollo โ†’ Express Middleware โ†’ Apollo Context -> Resolvers โ†’ Other Code ...โ†’ A REST call needing the header in original HTTP request
We have a working solution with the context, we were looking for a more global solution using middleware

mongoose and restify - localize strings before returning json

I would like to return localized Strings for multilanguage business objects in our RestFul API based on node.js, restify and mongoose. I have the requirement to store the translated resources on our translation resource server, but also need to support dynamic creation of those business objects.
I found a solution to easily plugin the i18n process in the POST/PUT calls using a single pre-'save' mongoose middleware on all Schema, when creating or updating my multi-languate business objects - this works because I am able to pass the request context to the obj.save(req, callback) call.
But, I am struggling to plug in the i18n on simple GETs. I thought of and tried different ways where I can plugin the i18n before returning the response, but don't really find a good way. Options I thought of:
translate in a mongoose middleware pre /post ('init'):
Problem: I don't have access to the request context, and therefore
don't know the locale to return, so I cannot translate there.
translate in the toObject() / toJSON {transform: }:
Same issue - i don't have the request context in these hooks.
translate in the handler/controller methods for each ressource.
Problem: Duplication, I have to do it everywhere, I would really prefer a solution I can define on the model/Schema layer
translate in a restify / express middleware towards the end:
Problem: I don't have access to the mongoose schema metainformation anymore, so I don't know which attriutes to translate.
Edit: just found this additional way:
- translate in a custom restify responseFormatter:
This seems to work nicely, in the reponseformatter I have access to everything I need. It kind of seems a little weird from an architechtural point of view, but if nobody has a better idea, I will add this as an answer.
Maybe (hopefully) I am missing something obvious...
thanks for any hints

Express & Socket.io Route parroting/copying/sharing

I'm working with expressjs and socket.io in nodejs. I'm looking into assign identical route handlers to requests made in either HTTP or via websockets/socket.io.
For instance:
var responder = function(req, res){
req.params //<-- {id: 'something...'}
}
app.get('/foo/:id', responder);
io.on('/foo/:id', responder);
socket.io doesn't appear to have this type of routing functionality. Does anyone know of a library/module to help with this?
There are several options.
If you'd like to keep using express, check out express.io.
If you don't mind using something a bit different, sails lets you do this sort of thing as well.
(Update: sails now uses express too)
Both have been used in production successfully.
Note that routing is also pretty simple to implement on your own. If you check out how express do it I'm sure you'll be able to figure out a slim implementation that would match you needs.
Good luck! Let me know what you ended up using and how it worked for you.

Resources