Express Nodejs
Express Nodejs
hey
') hb ‘application/json': function () { res.send({ message: ‘hey’ }) he default: function () { // 10g the request and respond with 406 res. status (406).send('Not Acceptable") 3 » In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation: hitpssexpressis.comfen4vapi.him!ssrargo2t Express 4x API Reference res. format({ text: function () { res.send(‘hey’) b html: function () { res. send('hey
') hb json: function () { res.send({ message: ‘hey’ )) y » res.get(field) Returns the HTTP response header specified by field. The match is case-insensitive, res.get('Content-Type') I) => “text/plain res,json([body]) Sends a JSON response. This method sends a response (with the correct content-ype) that is the parameter converted to a JSON string using JSON.stringify() The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON. res. json(null) res.json({ user: ‘tobi’ }) res. status (580). json({ error ‘message’ }) res.jsonp([body]) Sends a JSON response with JSONP support. This method is identical to res. json(), except that it opts-in to JSONP callback support. res. jsonp(null) // => callback(null) res.jsonp({ user: ‘tobi’ }) J/ => callback({ "user": obi" }) hitpssexpressis.comfen4vapi.him! 5018ssyz0r2024 Express 4x API Reference res.status(5@@).jsonp({ error: ‘message’ }) // => callback({ "error": “message” }) By default, the JSONP callback name is simply callback. Override this with the jsonp callback nae setting The following are some examples of JSONP responses using the same code: // 2callback=foo res. jsonp({ user: ‘tobi’ }) J] => foo({ “user”: "tobi" }) app.set('jsonp callback name’, ‘cb') 1] 2cb=Foo res. status (580). jsonp({ error: ‘message’ }) // => foo({ "error": “message” }) res.links(links) Joins the Links provided as properties of the parameter to populate the response’s Link HTTP header field For example, the following call: res. links ({ next: ‘http: //api.example.com/users?page=2' , last: ‘http: //api-example.com/users?page=5' » Yields the following results: Link: ‘/api.example.com/users?page=2>; rel="next", ://api.exanple.com/users?page-5>; rel="last" res.locat in(path) Sets the response Location HTTP header to the specified path parameter. res.location('/foo/bar') res. location( ‘http: //example. com’) res. location(‘back') A path value of "back" has a special meaning, it refers to the URL specified in the Referer header of the request. If the Referer header was not specified, it refers to“/", hitpssexpressis.comfen4vapi.him! S16searz02t Express 4x API Reference After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header, without any validation Browsers take the responsibilty of deriving the intended URL from the current URL or the referring URL, and the URL specified in the Location header; and redirect the user accordingly. res.redirect([status,] path) Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to "302 “Found” res.redirect(' /foo/bar') res.redirect( ‘http: //example.con* ) res.redirect(301, ‘http: //example.com’) res.redirect(*../login') Redirects can be a fully-qualified URL for redirecting to a different site: res.redirect( ‘http: //google. com’) Redirects can be relative to the root of the host name. For example, if the application is on http: //exampl e..com/admin/post/new, the following would redirect to the URL http: //example. com/admin: res.redirect('/admin') Redirects can be relative to the current URL. For example, from http: //example.com/blog/admin/ (notice the trailing slash), the following would redirect to the URL http: //example. com/blog/admin/post/new. res.redirect(‘post/new') Redirecting to post/new from http://example..com/b1og/adnin (no trailing slash), will redirect to http:// example. com/blog/post/new, Ifyou found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense. Path-relative redirects are also possible. If you were on http: //example.con/admin/post/new, the following would redirect to http: //example. com/admin/post: res.redirect(‘..') A back redirection redirects the request back to the referer, defaulting to / when the referer is missing, res.redirect(‘back') res.render(view [, locals] [, callback] hitpssexpressis.comfen4vapi.him! 5216ssyear2021 Express 4x API Reference Renders a view and sends the rendered HTML string to the client, Optional parameters: * locals, an object whose properties define local variables for the view. * callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes nex t(err) internally. ‘The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via require()) and render it using the loaded module’s _expre ss function, For more information, see Using template engines with Express. NOTE: The view argument performs file system operations like reading a file from disk and evaluating Node,js modules, and as so for security reasons should not contain input from the end-user. ‘The local variable cache enables view caching, Set it to true, to cache the view during development; view caching is enabled in production by default // send the rendered view to the client res.render('index') // if a callback is specified, the rendered HTML string has to be sent explicitly res.render(‘index', function (err, html) { res. send(html) » // pass a local variable to the view res.render(‘user', { name: ‘Tobi’ }, function (err, html) { Move » res.send([body]) Sends the HTTP response. The body parameter can be a Buffer object, a String, an object, Boolean, or an Array. For example: res. send(Buffer. from( whoop") res.send({ some: ‘json’ }) res.send("some html
") res.status(404).send(*Sorry, we cannot find that!") res.status(500).send({ error: ‘something blew up’ }) This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content -Length HTTP response header field (unless previously defined) and hitpssexpressis.comfen4vapi.him! saves,syporz0et Express 4x API Reference provides automatic HEAD and HTTP cache freshness support. When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream’, unless previously defined as shown below: res.set(*Content-Type’, ‘text/html') res. send(Buffer.from('some htnl
')) When the parameter is a String, the method sets the Content-Type to “text/htm!" res.send(‘sone html
') When the parameter is an Array or Object, Express responds with the JSON representation: res.send({ user: ‘tobi’ }) res.send([1, 2, 3]) res.sendFile(path [, options] [, fn]) res. sendFile() is supported by Express v4.8.0 onwards, Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename's extension. Unless the root option is set in the options object, path must be an absolute path to the file, ‘This API provides access to data on the running file system. Ensure that either (a) the way in which the path argument was constructed into an absolute path is secure if t contains user input or (b) set the rast option to the absolute path of a directory to contain access within, When the root option is provided, the path argument is allowed to be a relative path, including containing . . Express will validate that the relative path provided as path will resolve within the given root option. The following table provides details on the options parameter. Property Description Default Availability maxAge Sets the max-age property of the Cache-Control header in 0 milliseconds or a string in ms format root Root directory for relative filenames. lastModi | Sets the Last Modified header to the last modified date of Enabled | 4,9.0+ fied the file on the OS. Set false to disable it. headers | Object containing HTTP headers to serve with the file. dotfiles | Option for serving dotfiles. Possible values are “allow”, “ignore” “deny’, “ignore". hitpssfexpressis.comfeni4vapihim! saessarg02t Express 4x API Reference Property Description Default Availability acceptRa | Enable or disable accepting ranged requests. true 414+ nges cachecon Enable or disable setting Cache-Control response header. true 4.14+ trol immutabl | Enable or disable the inmutable directive inthe Cache-Cont false 4.16+ e rol response header. If enabled, the maxAge option should also be specified to enable caching. The inmutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed, 4 » The method invokes the callback function fn(err) when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route. Here is an example of using res. sendFile with all its arguments, app.get('/file/:name', function (req, res, next) { var options = { root: path. join(_dirname, ‘public'), dotfiles: ‘deny’, headers: { ‘x-timestamp': Date.now(), ‘x-sent': true var fileName = req.params.name res.sendFile(fileName, options, function (err) { if (err) { next (err) } else ¢ console. log("Sent:', fileName) , » » The following example illustrates using res. sendFile to provide fine-grained support for serving files: app.get(' /user/:uid/photos/:file’, function (req, res) { var wid = req.parans uid var file = req.params.file req.user.mayViewFilesFrom(uid, function (yes) { hitpssexpressis.comfen4vapihim! 55165searzo2t Express 4x API Reference if (yes) { res.sendFile('/uploads/' + uid + '/' + file) } else { res. status(4@3).send("Sorry! You can't see that.") ? » » For more information, or if you have issues or concerns, see send. res.sendStatus(statusCode) Sets the response HTTP status code to statusCode and sends its string representation as the response body. res.sendStatus(200) // equivalent to res. status(200).send(‘OK') res.sendStatus(403) // equivalent to res.status(4@3).send( ‘Forbidden’ ) res.sendStatus(404) // equivalent to res.status(4e4).send('Not Found") res.sendStatus(5@@) // equivalent to res. status(5@@).send('Internal Server Error’) fan unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body. Some versions of Node, will throw when res. statusCoce is set to an invalid HTTP status code (outside of the range 109 to 599). Consult the HTTP server documentation for the Node,js version being used, res.sendStatus(9999) // equivalent to res. status(9999) .send('9999") More about HTTP Status Codes res.set(field [, value]) Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter. res.set('Content-Type', ‘text/plain') res.set({ ‘content-Type’: ‘text/plain’, ‘Content-Length’: '123', ETag: '12345° » Aliased as res.header(Field [, value]). hitpssexpressis.comfen4vapi.him! eressirorz024 Express 4 API Reference res.status(code) Sets the HTTP status for the response. Itis a chainable alias of Node’s response.statusCode. res. status (403) .end() res. status (400).send('Bad Request") res.status (404). sendFile(' /absolute/path/to/404.png") res.type(type) Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified ty pe. If type contains the” character, then it sets the Content-Type to type. res.type(*.html*) // => ‘text/html! res.type(‘html") J] => text/html" res. type( json’) J/ => ‘application/json* res. type( ‘application/json") // => “application/json* res.type( png") J] => "image/png" res.vary(field) ‘Adds the field to the Vary response header, if it is not there already. res. vary(‘User-Agent') render('docs") Router Arouter object is an isolated instance of middleware and routes. You can think of it as a "mini- application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router. Arouter behaves like middleware itself, so you can use it as an argument to app.use() of as the argument to another router's use() method. The top-level express object has a Router() method that creates a new router object. Once you've created a router object, you can add middleware and HTTP method routes (such as get, put, p ost, and so on) to it just like an application. For example: // invoked for any requests passed to this router router.use(function (req, res, next) ( hitpssexpressis.comfen4vapi.him! 5718ssearzo2t Express 4x API Reference // s+ some logic here .. like any other middleware next() » // will handle any request that ends in /events // depends on where the router is “use()'d" router.get('/events', function (req, res, next) { Moe » You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps // only requests to /calendar/* will be sent to our “router” app. use(' /calendar’, router) Methods router.all(path, [callback, ...] callback) This method is just like the router .METHOD() methods, except that it matches all HTTP methods (verbs). This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next() to continue matching subsequent routes. router.all('*', requireauthentication, loaduser) Or the equivalent router.all('*', requireauthentication) router.all('*', loaduser) Another example of this is white-listed “global functionality. Here the example is much like before, but it only restricts paths prefixed with "/api” router.all('/api/*', requireduthentication) router.METHOD(path, [callback, callback) The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are router.get (), router. post(), router. put (), and so on. hitpssexpressis.comfen4vapi.him! satessy20r2024 xpress 4 API Reference ‘The router. get() function is automatically called for the HTTP HEAD method in addition to the GET method if rou ‘ter-head() was not called for the path before router. get() You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke next ‘route" ) to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched. ‘The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when performing these matches, for example "GET /" would match the following route, as would "GET /?name=tobi’. router.get(‘/', function (req, res) { res.send(‘hello world") » You can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c" as well as “GET /cornmits/71 dbb9c..4cO84F9" router. get(/*\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) { var from = req.parans[0] var to = req.params[2] || ‘HEAD’ res.send(‘conmit range ' + from + » + to) router.param(name, callback) Adds callback triggers to route parameters, where name is the name of the parameter and callback is the callback function. Although name is technically optional, using this method without it is deprecated starting with Express v4.1.0 (see below). ‘The parameters of the callback function are: * req, the request object. * res, the response object. * next, indicating the next middleware function, © The value of the name parameter. * The name of the parameter. Unlike app-paran(), router. param() does not accept an array of route parameters. For example, when :user is present in a route path, you may map user loading logic to automatically provide req. user to the route, or perform validations on the parameter input. router.param(‘user', function (req, res, next, id) { // try to get the user details from the User model and attach it to the request hitpssexpressis.comfen4vapihim! sossyz0r2024 Express 4x API Reference object User. find(id, function (err, user) ( if (err) { next(err) } else if (user) { req.user = user next () } else { next(new Error('failed to load user')) } » » Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on router will be triggered only by route parameters defined on router routes Aparam callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. router.param('id', function (req, res, next, id) ¢ console. log( “CALLED ONLY ONCE") next() » router.get(‘/user/:id', function (req, res, next) { console.log("although this matches") next() » router.get(‘/user/:id', function (req, res) { console. log(*and this matches too’) res.end() » On GET /user/42, the following is printed: CALLED ONLY ONCE although this matches and this matches too ‘The following section describes router. param(callback), which is deprecated as of v4.11.0. ‘The behavior of the router.param(name, callback) method can be altered entirely by passing only a function to router. param( ). This function is a custom implementation of how router.param(name, call back) should behave - it accepts two parameters and must return a middleware. hitps:ifexpressis.cmven/4xapi. html 60185sirorz024 Express 4 API Reference The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation, The middleware returned by the function decides the behavior of what happens when a URL parameter is captured. In this example, the router.param(name, callback) signature is modified to router.param(name, acces Td). Instead of accepting a name and a callback, router.param() will now accept a name and a number. var express = require('express') var app = express() var router = express.Router() J/ customizing the behavior of router.param() router.param(function (param, option) { return function (req, res, next, val) { if (val === option) ¢ next(), } else { res.sendStatus (403) } + » // using the customized router.param() router.param("id', '1337") // route to trigger the capture router.get(‘/user/:id', function (req, res) { res.send(‘OK") » app. use(router) app. listen(30@0, function () { console. log(‘ Ready’) » In this example, the router.param(name, callback) signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id router.param(function (param, validator) ( return function (req, res, next, val) { if (validator(val)) { next(), } else { hitpssexpressis.comfen4vapihim! Crdsearzo2t Express 4x API Reference res. sendStatus (403) } » router.paran(‘id', function (candidate) { return lisNaN(parseFloat (candidate) 8& isFinite(candidate) » router.route(path) Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use router.route() to avoid duplicate route naming and thus typing errors. Building on the router.param() example above, the following code shows how to use router.route() to specify various HTTP method handlers. var router = express.Router() router.param(‘user_id’, function (req, res, next, id) // sample user, would actually fetch from 0B, etc... req.user : id, name: °T3" + next() » router.route('/users/:user_id') sll (function (req, res, next) ( // vuns for all HTTP verbs first // think of it as route specific middleware! next() » aget (function (req, res, next) { res. json(req.user) » -put(Function (neq, res, next) { // just an example of maybe updating the user req.user.name = req.params.name // save user ... etc res. json(req.user) » -post (function (req, res, next) { next (new Error(‘not implenented')) » -delete(function (req, res, next) { hitpssexpressis.comfen4vapi.him! 6ssearzo2t Express 4x API Reference next(new Error(‘not implemented’ )) » This approach re-uses the single /users/:user_id path and adds handlers for various HTTP methods. NOTE: When you use router.route(), middleware ordering is based on when the routelis created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added, router.use([path], [function, ...] function) Uses the specified middleware function or functions, with optional rnount path path, that defaults to "/”. This method is similar to app.use(). A simple example and use case is described below. See app.use() for more information. Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match var express = require(‘express') var app = express() var router = express.Router() // simple logger for this router's requests // all requests to this router will first hit this middleware router.use(function (req, res, next) { console.log("%s %s %s', req.method, req.url, req.path) next() » // this will only be invoked if the path starts with /bar from the mount point router.use('/bar’, function (req, res, next) ( // ++. maybe some additional /bar logging ... next() » // always invoked router.use(function (req, res, next) ( res.send( ‘Hello World") » app-use("/foo", router) app. Listen (3000) The “mount” path is stripped and is not visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” hitpssexpressis.comfen4vapi.him! eaves,ssrargo2t Express 4x API Reference pathname The order in which you define middleware with router .use() is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged var logger = require('morgan’) var path = require('path') router. use(logger()) router.use(express.static(path. join(_dirname, ‘public’))) router.use(function (req, res) { res.send(‘Hello') » Now suppose you wanted to ignore logging requests for static files, but to continue logging routes and middleware defined after logger(). You would simply move the call to express.static() to the top, before adding the logger middleware: router .use(express.static(path.join(__dirname, ‘public'))) router.use(logger()) router.use(function (req, res) { res.send(‘Hello') » Another example is serving files from multiple directories, giving precedence to “/public” over the others: router.use(express.static(path. join(_dirname, ‘public’))) router. use (express. static(path. join(_dirname, ‘files'))) router. use(express. static(path. join(_dirname, ‘uploads'))) ‘The router.use() method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters. NOTE: Although these middleware functions are added via a particular router, when they run is defined by the path they are attached to (not the router), Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path: var authRouter = express.Router() var openRouter = express. Router() authRouter.use(require(. /authenticate').basic(usersdb)) authRouter.get(‘/:user_id/edit', function (req, res, next) ( 71 ss. Edit user UT. » openkouter.get('/', function (req, res, next) ( hitpssexpressis.comfen4vapi.him! Crd