res.json() vs res.send() vs res.end() in Express

Express is one of the most popular web frameworks for Node.js - probably used by most Node.js developers. It's an excellent framework that has a myriad of HTTP utility methods, and it also performs well.

When working with Express, we get access to a request and a response object, and we can use the latter to send some response back to the requester. There are a bunch of methods available for us such as res.json() , res.send() and res.end() . The question is, of course, are these different, if so how. In this article, we'll review these differences.

Whenever an Express application server receives an HTTP request, it will provide the developer with an object, commonly referred to as res . Here's a really simple example:

The res object is an enhanced version of the response object found in Node.js.

Sending a response

There are multiple ways to send responses using Express, and we'll go through a few examples now.

Sending a response can be achieved by calling the res.send() method. The signature of this method looks like this: res.send([body]) where the body can be any of the following: Buffer , String , an Object and an Array .

This method automatically sets the Content-Type response header as well based on the argument passed to the send() method, so for example if the [body] is a Buffer the Content-Type will be set to application/octet-stream unless of course we programmatically set it to be something else.

Programmatically setting the Content-Type header is possible via the set() method on the res object: res.set('Content-Type', 'text/html'); .

Many developers out there are using Express to create RESTful APIs, and most of the time such APIs return JSON data. Now the question is of course, should we use res.send() to return JSON data - since this method accepts objects as part of its argument - or should we use res.json() ?

Let's see what happens when we try to send JSON data:

The response header looks like this:

We can see that Express has correctly set the 'Content-Type'. So if this works, why would Express expose res.json() at all?

res.json() actually has some functionality that is related to JSON objects that we can't access when using res.send() . Namely, it can format the returned JSON data by applying two options:

These two options are collected and passed to the JSON.stringify() method: since its signature loos like this: JSON.stringify(object, replacer, space ) . Once this method is called, the res.json() method will then call res.send() as well under the hood.

Last but not least let's take a look at res.end() . Do we need to call it?

Take a look at this article and see what happens when you don't call res.end() : Concurrent HTTP connections in Node.js

This method kind of makes sense, right? There's a response and once we have collected the data or did something else we want to present that to the caller and as a last step we should end the session - this could be achieved by calling res.end() . But do we need it? The answer is two-fold: yes and no.

We can use res.end() if we want to end the response without providing any data. This could be useful for a 404 page, for example:

In the code above we are explicitly setting the HTTP status code and immediately after that ending the response.

But what if we want to send some data and end the response? The answer is simple, res.send() (and remember, res.json() ) both allow us to send some data and they also end the response, so there's no need to explicitly call res.end() .

Please also note that res.end() does not send an ETag header for the HTTP response whereas res.send() does. This Entity Tag header is important when working with web cache validation - it helps caches to be more efficient as well as saves bandwidth.

To sum things up, res.json() allows for extra formatting of the JSON data - if this is not required res.send() can also be used to return a response object using Express. Both of these methods also end the response correctly, and there's no further action required.

Front-end Tutorials

Front-end Tutorials

Server-Side Tutorials

Server-Side Tutorials

CMS Tutorials

CMS Tutorials

Logo

Express.js Basic

  • express Intro
  • express express()
  • express Application
  • express Request
  • res.headersSent
  • res.append()
  • res.attachment()
  • res.cookie()
  • res.clearCookie()
  • res.download()
  • res.format()
  • res.jsonp()
  • res.links()
  • res.location()
  • res.redirect()
  • res.render()
  • res.sendFile()
  • res.sendStatus()
  • res.status()
  • express Router

Express res.json() Method

Express res.json() Method

Photo Credit to CodeToFun

🙋 Introduction

In the world of web development, efficient handling and formatting of responses are crucial.

Express.js, a powerful web application framework for Node.js, provides the res.json() method for sending JSON responses to clients.

Join us as we explore the syntax, usage, and practical examples of this handy Express.js feature.

The syntax for the res.json() method is straightforward:

  • status (optional): The HTTP response status code. If not specified, it defaults to 200.
  • body (optional): The JSON data to be sent in the response.

❓ How res.json() Works

The res.json() method simplifies the process of sending JSON responses to clients. It automatically sets the Content-Type header to application/json and converts the provided JSON object into a string for transmission.

In this example, the res.json() method is used to send a JSON response containing user information.

📚 Use Cases

Api responses:.

Use res.json() to send JSON responses when building APIs, providing structured data to clients.

Error Responses:

Leverage res.json() for sending error responses in a consistent JSON format.

🏆 Best Practices

Set appropriate status codes:.

Specify the appropriate HTTP status code based on the nature of the response. For success, use 200 , and for errors, choose relevant codes like 404 or 500 .

Handle Asynchronous Operations:

Ensure that the res.json() method is called only once in asynchronous operations to prevent headers from being sent multiple times.

🎉 Conclusion

The res.json() method in Express.js simplifies the process of sending JSON responses, making it an essential tool for building modern web applications. Whether you're creating APIs or handling error responses, understanding how to use res.json() effectively enhances the communication between your server and clients.

Now, equipped with knowledge about the res.json() method, go ahead and streamline your JSON responses in your Express.js projects!

đŸ‘šâ€đŸ’» Join our Community:

Join Our Telegram Channel

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com .

Buy me a coffee to make codetofun.com free for everyone.

Share Your Findings to All

Recent post in express.

Express res.append() Method

Express res.append() Method

Express res.attachment() Method

Express res.attachment() Method

Express res.type() Method

Express res.type() Method

Express res.set() Method

Express res.set() Method

Express res.status() Method

Express res.status() Method

Express res.sendStatus() Method

Express res.sendStatus() Method

Express res.vary() Method

Express res.vary() Method

Search any post, recent post (others).

jQuery :animated Selector

jQuery :animated Selector

jQuery :even Selector

jQuery :even Selector

jQuery :enabled Selector

jQuery :enabled Selector

jQuery :empty Selector

jQuery :empty Selector

jQuery :disabled Selector

jQuery :disabled Selector

jQuery :file Selector

jQuery :file Selector

jQuery :first-child Selector

jQuery :first-child Selector

guest

If you have any doubts regarding this article ( Express res.json() Method ), please comment here. I will help you immediately.

Server-Sent Events with Express

Server-sent events are a new HTTP API for pushing events from the server to the client. Unlike websockets , server-sent events (SSE for short) are built on top of the HTTP protocol, so no need for ws:// URLs or additional npm modules. Server-side events also handle reconnecting automatically , so you don't have to write code to reconnect if the connection is lost.

Getting Started

On the client side, you use the EventSource class to connect to a server-side event source. The client side is easy: just point the EventSource class to an Express route that's configured to handle SSE and add an event listener .

The Express side is the tricky part. To support SSE, you need to set 3 headers, and then send the headers to the client using flushHeaders() :

  • Cache-Control: no-cache
  • Content-Type: text/event-stream : So the client knows this response is an HTTP stream
  • Connection: keep-alive : So Node.js knows to keep the HTTP socket open

Once you've called flushHeaders() , you can then start writing events using the res.write() function . The res.write() function writes to the HTTP connection without explicitly ending the HTTP response. Make sure you do not use res.send() or res.end() , because those explicitly end the response.

Below is an example of a standalone Express server that handles SSE with the /events endpoint:

Run the above server and navigate to http://localhost:3000 , you should see the below:

  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters

res write json

More Express Tutorials

  • Handle POST Form Data with Express JS
  • What Does `app.use(express.json())` Do in Express?
  • Handling POST Requests with Express
  • What Does `app.use(express.static())` Do in Express?
  • The `app.get()` Function in Express
  • The `app.use()` Function in Express
  • Express Template Engines
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Response: json() method

The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

Note that despite the method being named json() , the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

Return value

A Promise that resolves to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number


In our fetch JSON example (run fetch JSON live ), we create a new request using the Request() constructor, then use it to fetch a .json file. When the fetch is successful, we read and parse the data using json() , then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • ServiceWorker API
  • Cross-Origin Resource Sharing (CORS)

res write json

About the author

res write json

Stay Informed

It's important to keep up with industry - subscribe ! to stay ahead

All right! Thank you, you've been subscribed.

Top developers

res write json

Related articles

res write json

An Introduction to Clustering in Node.js

Picture your Node.js app starts to slow down as it gets bombarded with user requests. It's like a traffic jam for your app, and no developer likes ...

res write json

JAMstack Architecture with Next.js

The Jamstack architecture, a term coined by Mathias Biilmann, the co-founder of Netlify, encompasses a set of structural practices that rely on ...

res write json

Rendering Patterns: Static and Dynamic Rendering in Nextjs

Next.js is popular for its seamless support of static site generation (SSG) and server-side rendering (SSR), which offers developers the flexibility ...

No comments yet

Or use a social network account

By Signing In \ Signing Up, you agree to our privacy policy

Sign in \ Sign Up

Or use email\username to sign in

Password recovery

You can also try to sign in here

Insert/edit link

Enter the destination URL

Or link to existing content

  • Hello world
  • Express generator
  • Basic routing
  • Static files
  • More examples
  • Writing middleware
  • Using middleware
  • Overriding the Express API
  • Using template engines
  • Error handling
  • Express behind proxies
  • Moving to Express 4
  • Moving to Express 5
  • Database integration
  • 3.x (deprecated)
  • 2.x (deprecated)
  • Template engines
  • Process managers
  • Security updates
  • Security best practices
  • Performance best practices
  • Health checks and graceful shutdown
  • Template Engines
  • Utility modules
  • Companies using Express
  • Open-source projects
  • Additional learning
  • Contributing to Express
  • Release Change Log
  • express.json()
  • express.raw()
  • express.Router()
  • express.static()
  • express.text()
  • express.urlencoded()

app.mountpath

  • app.delete()
  • app.disable()
  • app.disabled()
  • app.enable()
  • app.enabled()
  • app.engine()
  • app.listen()
  • app.METHOD()
  • app.param()
  • app.render()
  • app.route()

req.baseUrl

Req.cookies, req.hostname, req.originalurl, req.protocol, req.signedcookies, req.subdomains.

  • req.accepts()
  • req.acceptsCharsets()
  • req.acceptsEncodings()
  • req.acceptsLanguages()
  • req.param()
  • req.range()

res.headersSent

  • res.append()
  • res.attachment()
  • res.cookie()
  • res.clearCookie()
  • res.download()
  • res.format()
  • res.jsonp()
  • res.links()
  • res.location()
  • res.redirect()
  • res.render()
  • res.sendFile()
  • res.sendStatus()
  • res.status()
  • router.all()
  • router.METHOD()
  • router.param()
  • router.route()
  • router.use()

Creates an Express application. The express() function is a top-level function exported by the express module.

express.json([options])

This middleware is available in Express v4.16.0 onwards.

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser .

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( {} ) if there was no body to parse, the Content-Type was not matched, or an error occurred.

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The following table describes the properties of the optional options object.

express.raw([options])

This middleware is available in Express v4.17.0 onwards.

This is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser .

Returns middleware that parses all bodies as a Buffer and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body Buffer containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( {} ) if there was no body to parse, the Content-Type was not matched, or an error occurred.

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.toString() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a Buffer before calling buffer methods is recommended.

express.Router([options])

Creates a new router object.

The optional options parameter specifies the behavior of the router.

You can add middleware and HTTP method routes (such as get , put , post , and so on) to router just like an application.

For more information, see Router .

express.static(root, [options])

This is a built-in middleware function in Express. It serves static files and is based on serve-static .

NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.

The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it calls next() to move on to the next middleware, allowing for stacking and fall-backs.

The following table describes the properties of the options object. See also the example below .

For more information, see Serving static files in Express . and Using middleware - Built-in middleware .

Possible values for this option are:

  • “allow” - No special treatment for dotfiles.
  • “deny” - Deny a request for a dotfile, respond with 403 , then call next() .
  • “ignore” - Act as if the dotfile does not exist, respond with 404 , then call next() .

NOTE : With the default value, it will not ignore files in a directory that begins with a dot.

fallthrough

When this option is true , client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call next() to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke next(err) .

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.

The signature of the function is:

  • res , the response object .
  • path , the file path that is being sent.
  • stat , the stat object of the file that is being sent.

Example of express.static

Here is an example of using the express.static middleware function with an elaborate options object:

express.text([options])

This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on body-parser .

Returns middleware that parses all bodies as a string and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body string containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( {} ) if there was no body to parse, the Content-Type was not matched, or an error occurred.

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.trim() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a string before calling string methods is recommended.

express.urlencoded([options])

This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser .

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( {} ) if there was no body to parse, the Content-Type was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when extended is false ), or any type (when extended is true ).

Application

The app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module:

The app object has methods for

  • Routing HTTP requests; see for example, app.METHOD and app.param .
  • Configuring middleware; see app.route .
  • Rendering HTML views; see app.render .
  • Registering a template engine; see app.engine .

It also has settings (properties) that affect how the application behaves; for more information, see Application settings .

The Express application object can be referred from the request object and the response object as req.app , and res.app , respectively.

The app.locals object has properties that are local variables within the application, and will be available in templates rendered with res.render .

The locals object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app )

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

A sub-app is an instance of express that may be used for handling the request to a route.

It is similar to the baseUrl property of the req object, except req.baseUrl returns the matched URL path, instead of the matched patterns.

If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on, as shown in the following example.

app.on('mount', callback(parent))

The mount event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.

Sub-apps will:

  • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  • Inherit the value of settings with no default value.

For details, see Application settings .

app.all(path, callback [, callback ...])

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.

The following callback is executed for requests to /secret whether using GET, POST, PUT, DELETE, or any other HTTP request method:

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on 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.

Or the equivalent:

Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:

app.delete(path, callback [, callback ...])

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide .

app.disable(name)

Sets the Boolean setting name to false , where name is one of the properties from the app settings table . Calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo') .

For example:

app.disabled(name)

Returns true if the Boolean setting name is disabled ( false ), where name is one of the properties from the app settings table .

app.enable(name)

Sets the Boolean setting name to true , where name is one of the properties from the app settings table . Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo') .

app.enabled(name)

Returns true if the setting name is enabled ( true ), where name is one of the properties from the app settings table .

app.engine(ext, callback)

Registers the given template engine callback as ext .

By default, Express will require() the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.

Use this method for engines that do not provide .__express out of the box, or if you wish to “map” a different extension to the template engine.

For example, to map the EJS template engine to “.html” files:

In this case, EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback) , though note that it aliases this method as ejs.__express internally so if you’re using “.ejs” extensions you don’t need to do anything.

Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

app.get(name)

Returns the value of name app setting, where name is one of the strings in the app settings table . For example:

app.get(path, callback [, callback ...])

Routes HTTP GET requests to the specified path with the specified callback functions.

For more information, see the routing guide .

app.listen(path, [callback])

Starts a UNIX socket and listens for connections on the given path. This method is identical to Node’s http.Server.listen() .

app.listen([port[, host[, backlog]]][, callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen() .

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

The app returned by express() is in fact a JavaScript Function , designed to be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

NOTE: All the forms of Node’s http.Server.listen() method are in fact actually supported.

app.METHOD(path, callback [, callback ...])

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get() , app.post() , app.put() , and so on. See Routing methods below for the complete list.

Routing methods

Express supports the following routing methods corresponding to the HTTP methods of the same names:

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.

To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ... .

The app.get() function is automatically called for the HTTP HEAD method in addition to the GET method if app.head() was not called for the path before app.get() .

The method, app.all() , is not derived from any HTTP method and loads middleware at the specified path for all HTTP request methods. For more information, see app.all .

For more information on routing, see the routing guide .

app.param([name], callback)

Add callback triggers to route parameters , where name is the name of the parameter or an array of them, and callback is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

If name is an array, the callback trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to next inside the callback will call the callback for the next declared parameter. For the last parameter, a call to next will call the next middleware in place for the route currently being processed, just like it would if name were just a string.

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.

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 app will be triggered only by route parameters defined on app routes.

All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

On GET /user/42 , the following is printed:

On GET /user/42/3 , the following is printed:

The following section describes app.param(callback) , which is deprecated as of v4.11.0.

The behavior of the app.param(name, callback) method can be altered entirely by passing only a function to app.param() . This function is a custom implementation of how app.param(name, callback) should behave - it accepts two parameters and must return a middleware.

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 app.param(name, callback) signature is modified to app.param(name, accessId) . Instead of accepting a name and a callback, app.param() will now accept a name and a number.

In this example, the app.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.

The ‘ . ’ character can’t be used to capture a character in your capturing regexp. For example you can’t use '/user-.+/' to capture 'users-gami' , use [\\s\\S] or [\\w\\W] instead (as in '/user-[\\s\\S]+/' .

Returns the canonical path of the app, a string.

The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use req.baseUrl to get the canonical path of the app.

app.post(path, callback [, callback ...])

Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide .

app.put(path, callback [, callback ...])

Routes HTTP PUT requests to the specified path with the specified callback functions.

app.render(view, [locals], callback)

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render() , except it cannot send the rendered view to the client on its own.

Think of app.render() as a utility function for generating rendered view strings. Internally res.render() uses app.render() to render views.

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 is reserved for enabling view cache. Set it to true , if you want to cache view during development; view caching is enabled in production by default.

app.route(path)

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

app.set(name, value)

Assigns setting name to value . You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table .

Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo') . Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo') .

Retrieve the value of a setting with app.get() .

Application Settings

The following table lists application settings.

Note that sub-apps will:

  • Inherit the value of settings with no default value; these are explicitly noted in the table below.

Exceptions: Sub-apps will inherit the value of trust proxy even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of view cache in production (when NODE_ENV is “production”).

Options for `trust proxy` setting

Read Express behind proxies for more information.

Options for `etag` setting

NOTE : These settings apply only to dynamic files, not static files. The express.static middleware ignores these settings.

The ETag functionality is implemented using the etag package. For more information, see its documentation.

app.use([path,] callback [, callback...])

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path .

Description

A route will match any path that follows its path immediately with a “ / ”. For example: app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.

Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app. For example, this middleware function will be executed for every request to the app:

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

Error-handling middleware

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: Error handling .

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next) ):

Path examples

The following table provides some simple examples of valid path values for mounting middleware.

Middleware callback function examples

The following table provides some simple examples of middleware functions that can be used as the callback argument to app.use() , app.METHOD() , and app.all() . Even though the examples are for app.use() , they are also valid for app.use() , app.METHOD() , and app.all() .

Following are some examples of using the express.static middleware in an Express app.

Serve static content for the app from the “public” directory in the application directory:

Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:

Disable logging for static content requests by loading the logger middleware after the static middleware:

Serve static files from multiple directories, but give precedence to “./public” over the others:

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res ) but its actual name is determined by the parameters to the callback function in which you’re working.

But you could just as well have:

The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods .

In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use multipart-handling middleware like busboy , multer , formidable , multiparty , connect-multiparty , or pez .

This property holds a reference to the instance of the Express application that is using the middleware.

If you follow the pattern in which you create a module that just exports a middleware function and require() it in your main file, then the middleware can access the Express instance via req.app

The URL path on which a router instance was mounted.

The req.baseUrl property is similar to the mountpath property of the app object, except app.mountpath returns the matched path pattern(s).

Even if you use a path pattern or a set of path patterns to load the router, the baseUrl property returns the matched string, not the pattern(s). In the following example, the greet router is loaded on two path patterns.

When a request is made to /greet/jp , req.baseUrl is “/greet”. When a request is made to /hello/jp , req.baseUrl is “/hello”.

Contains key-value pairs of data submitted in the request body. By default, it is undefined , and is populated when you use body-parsing middleware such as express.json() or express.urlencoded() .

The following example shows how to use body-parsing middleware to populate req.body .

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {} .

If the cookie has been signed, you have to use req.signedCookies .

For more information, issues, or concerns, see cookie-parser .

When the response is still “fresh” in the client’s cache true is returned, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent.

When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent.

Further details for how cache validation works can be found in the HTTP/1.1 Caching Specification .

Contains the hostname derived from the Host HTTP header.

When the trust proxy setting does not evaluate to false , this property will instead get the value from the X-Forwarded-Host header field. This header can be set by the client or by the proxy.

If there is more than one X-Forwarded-Host header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

Prior to Express v4.17.0, the X-Forwarded-Host could not contain multiple values or be present more than once.

Contains the remote IP address of the request.

When the trust proxy setting does not evaluate to false , the value of this property is derived from the left-most entry in the X-Forwarded-For header. This header can be set by the client or by the proxy.

When the trust proxy setting does not evaluate to false , this property contains an array of IP addresses specified in the X-Forwarded-For request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

For example, if X-Forwarded-For is client, proxy1, proxy2 , req.ips would be ["client", "proxy1", "proxy2"] , where proxy2 is the furthest downstream.

Contains a string corresponding to the HTTP method of the request: GET , POST , PUT , and so on.

req.url is not a native Express property, it is inherited from Node’s http module .

This property is much like req.url ; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.

req.originalUrl is available both in middleware and router objects, and is a combination of req.baseUrl and req.url . Consider following example:

This property is an object containing properties mapped to the named route “parameters” . For example, if you have the route /user/:name , then the “name” property is available as req.params.name . This object defaults to {} .

When you use a regular expression for the route definition, capture groups are provided in the array using req.params[n] , where n is the n th capture group. This rule is applied to unnamed wild card matches with string routes such as /file/* :

If you need to make changes to a key in req.params , use the app.param handler. Changes are applicable only to parameters already defined in the route path.

Any changes made to the req.params object in a middleware or route handler will be reset.

NOTE: Express automatically decodes the values in req.params (using decodeURIComponent ).

Contains the path part of the request URL.

When called from a middleware, the mount point is not included in req.path . See app.use() for more details.

Contains the request protocol string: either http or (for TLS requests) https .

When the trust proxy setting does not evaluate to false , this property will use the value of the X-Forwarded-Proto header field if present. This header can be set by the client or by the proxy.

This property is an object containing a property for each query string parameter in the route. When query parser is set to disabled, it is an empty object {} , otherwise it is the result of the configured query parser.

As req.query ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The value of this property can be configured with the query parser application setting to work how your application needs it. A very popular query string parser is the qs module , and this is used by default. The qs module is very configurable with many settings, and it may be desirable to use different settings than the default to populate req.query :

Check out the query parser application setting documentation for other customization options.

This property holds a reference to the response object that relates to this request object.

Contains the currently-matched route, a string. For example:

Example output from the previous snippet:

A Boolean property that is true if a TLS connection is established. Equivalent to:

When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on req.cookie values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).

If no signed cookies are sent, the property defaults to {} .

Indicates whether the request is “stale,” and is the opposite of req.fresh . For more information, see req.fresh .

An array of subdomains in the domain name of the request.

The application property subdomain offset , which defaults to 2, is used for determining the beginning of the subdomain segments. To change this behavior, change its value using app.set .

A Boolean property that is true if the request’s X-Requested-With header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.

req.accepts(types)

Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns false (in which case, the application should respond with 406 "Not Acceptable" ).

The type value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the best match (if any).

For more information, or if you have issues or concerns, see accepts .

req.acceptsCharsets(charset [, ...])

Returns the first accepted charset of the specified character sets, based on the request’s Accept-Charset HTTP header field. If none of the specified charsets is accepted, returns false .

req.acceptsEncodings(encoding [, ...])

Returns the first accepted encoding of the specified encodings, based on the request’s Accept-Encoding HTTP header field. If none of the specified encodings is accepted, returns false .

req.acceptsLanguages([lang, ...])

Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field. If none of the specified languages is accepted, returns false .

If no lang argument is given, then req.acceptsLanguages() returns all languages from the HTTP Accept-Language header as an Array .

Express (4.x) source: request.js line 179

Accepts (1.3) source: index.js line 195

req.get(field)

Returns the specified HTTP request header field (case-insensitive match). The Referrer and Referer fields are interchangeable.

Aliased as req.header(field) .

req.is(type)

Returns the matching content type if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the type parameter. If the request has no body, returns null . Returns false otherwise.

For more information, or if you have issues or concerns, see type-is .

req.param(name [, defaultValue])

Deprecated. Use either req.params , req.body or req.query , as applicable.

Returns the value of param name when present.

Lookup is performed in the following order:

Optionally, you can specify defaultValue to set a default value if the parameter is not found in any of the request objects.

Direct access to req.body , req.params , and req.query should be favoured for clarity - unless you truly accept input from each object.

Body-parsing middleware must be loaded for req.param() to work predictably. Refer req.body for details.

req.range(size[, options])

Range header parser.

The size parameter is the maximum size of the resource.

The options parameter is an object that can have the following properties.

An array of ranges will be returned or negative numbers indicating an error parsing.

  • -2 signals a malformed header string
  • -1 signals an unsatisfiable range

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

In this documentation and by convention, the object is always referred to as res (and the HTTP request is req ) but its actual name is determined by the parameters to the callback function in which you’re working.

The res object is an enhanced version of Node’s own response object and supports all built-in fields and methods .

res.app is identical to the req.app property in the request object.

Boolean property that indicates if the app sent HTTP headers for the response.

Use this property to set variables accessible in templates rendered with res.render . The variables set on res.locals are available within a single request-response cycle, and will not be shared between requests.

In order to keep local variables for use in template rendering between requests, use app.locals instead.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.

res.append(field [, value])

res.append() is supported by Express v4.11.0+

Appends the specified value to the HTTP response header field . If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

Note: calling res.set() after res.append() will reset the previously-set header value.

res.attachment([filename])

Sets the HTTP response Content-Disposition header field to “attachment”. If a filename is given, then it sets the Content-Type based on the extension name via res.type() , and sets the Content-Disposition “filename=” parameter.

res.cookie(name, value [, options])

Sets cookie name to value . The value parameter may be a string or object converted to JSON.

All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265 .

You can set multiple cookies in a single response by calling res.cookie multiple times, for example:

The encode option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.

Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.

The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.

You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.

When using cookie-parser middleware, this method also supports signed cookies. Simply include the signed option set to true . Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.

Later you may access this value through the req.signedCookie object.

res.clearCookie(name [, options])

Clears the cookie specified by name . For details about the options object, see res.cookie() .

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie() , excluding expires and maxAge .

res.download(path [, filename] [, options] [, fn])

Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is derived from the path argument, but can be overridden with the filename parameter. If path is relative, then it will be based on the current working directory of the process or the root option, if provided.

This API provides access to data on the running file system. Ensure that either (a) the way in which the path argument was constructed is secure if it contains user input or (b) set the root option to the absolute path of a directory to contain access within.

When the root option is provided, 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.

The optional options argument is supported by Express v4.16.0 onwards.

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.

res.end([data] [, encoding])

Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse .

Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json() .

res.format(object)

Performs content-negotiation on the Accept HTTP header on the request object, when present. It uses req.accepts() to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the default callback.

The Content-Type response header is set when a callback is selected. However, you may alter this within the callback using methods such as res.set() or res.type() .

The following example would respond with { "message": "hey" } when the Accept header field is set to “application/json” or “*/json” (however if it is “*/*”, then the response will be “hey”).

In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:

res.get(field)

Returns the HTTP response header specified by field . The match is case-insensitive.

res.json([body])

Sends a JSON response. This method sends a response (with the correct content-type) 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.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.

By default, the JSONP callback name is simply callback . Override this with the jsonp callback name setting.

The following are some examples of JSONP responses using the same code:

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:

Yields the following results:

res.location(path)

Sets the response Location HTTP header to the specified path parameter.

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 “/”.

See also Security best practices: Prevent open redirect vulnerabilities .

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 responsibility 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”.

Redirects can be a fully-qualified URL for redirecting to a different site:

Redirects can be relative to the root of the host name. For example, if the application is on http://example.com/admin/post/new , the following would redirect to the URL http://example.com/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 .

Redirecting to post/new from http://example.com/blog/admin (no trailing slash), will redirect to http://example.com/blog/post/new .

If you 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.com/admin/post/new , the following would redirect to http://example.com/admin/post :

A back redirection redirects the request back to the referer , defaulting to / when the referer is missing.

res.render(view [, locals] [, callback])

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 next(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 __express function.

For more information, see Using template engines with Express .

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.

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:

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 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:

When the parameter is a String , the method sets the Content-Type to “text/html”:

When the parameter is an Array or Object , Express responds with the JSON representation:

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 it contains user input or (b) set the root 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.

Here is an example of using res.sendFile with all its arguments.

The following example illustrates using res.sendFile to provide fine-grained support for serving files:

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 the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

Some versions of Node.js will throw when res.statusCode is set to an invalid HTTP status code (outside of the range 100 to 599 ). Consult the HTTP server documentation for the Node.js version being used.

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.

Aliased as res.header(field [, value]) .

res.status(code)

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode .

res.type(type)

Sets the Content-Type HTTP header to the MIME type as determined by the specified type . If type contains the “/” character, then it sets the Content-Type to the exact value of type , otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the express.static.mime.lookup() method.

res.vary(field)

Adds the field to the Vary response header, if it is not there already.

A router 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.

A router behaves like middleware itself, so you can use it as an argument to app.use() or 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 , post , and so on) to it just like an application. For example:

You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.

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.

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.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.

The router.get() function is automatically called for the HTTP HEAD method in addition to the GET method if router.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”.

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 /commits/71dbb9c..4c084f9”.

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.11.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.param() , router.param() does not accept an array of route parameters.

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.

A param 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.

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, callback) should behave - it accepts two parameters and must return a middleware.

In this example, the router.param(name, callback) signature is modified to router.param(name, accessId) . Instead of accepting a name and a callback, router.param() will now accept a name and a number.

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.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.

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 route is 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 mount 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.

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” 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.

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:

Another example is serving files from multiple directories, giving precedence to “./public” over the others:

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:

Even though the authentication middleware was added via the authRouter it will run on the routes defined by the openRouter as well since both routers were mounted on /users . To avoid this behavior, use different paths for each router.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Node HTTP tutorial

last modified October 18, 2023

In this article we show how to create HTTP server and client applications in JavaScript with HTTP module.

HTTP is a Node.js module which can be used to create HTTP server and client applications in JavaScript. Popular JavaScript frameworks including Express and HapiJS are built on top of the HTTP module.

This tutorial teaches you the basics of HTTP interaction. To create real web applications, we should use a complete web framework such as JavaScript's Express or PHP's Symfony.

Setting up HTTP

First, we install the HTTP module.

We initiate a new Node.js application.

We install HTTP with npm i http command.

Node HTTP simple server

A server application is created with createServer .

The example creates a very simple HTTP server which sends a text message to the client. The server runs on port 8080.

First, we include the HTTP module.

We create a web application with the createServer function. It accepts a handler function which receives two parameters: the request and response objects.

With the writeHead method, we write a header to the response. We specify the status code and the content type.

We write data to the response.

We send the response to the client.

We start the server.

With the curl tool, we create a GET request to the server and receive the message.

Node HTTP send JSON

In the next example, we create a server that sends a JSON response. JSON (JavaScript Object Notation) is a lightweight data-interchange format.

The application responds to the /now request path by sending current date in JSON.

We check if the request URL is equal to /now .

We inform the client that we send JSON response in the header with the appropriate content type.

We write the current date in JSON to the response.

Node HTTP send HTML

Next, we are going to send HTML data to the client.

We specify the text/html content type and write HTML tags to the response.

Node HTTP query parameters

Clients can communicate with servers by adding query parameters to the URL.

In the example, the server responds with a message built from query parameters.

To parse the query parameters, we use the url module.

We get the query object which has the values.

We build the message from the query parameters.

After we start the server, we create a request with curl . We specify the query parameters.

Node HTTP server

The following example creates a more complex HTTP server. We have three HTML files in the docs subdirectory.

This is the about.html file.

This is the contact.html file.

This is the index.html file.

We use the fs module to read the HTML files.

The example reads HTML files from the filesystem.

We determine the pathname, which is the file name to be loaded.

For the root page, we send index.html .

With the readFile method, we read the contents of the HTML file.

In case of an error, we send 404 code to the client.

If the file was found and read, we send the contents of the file to the client.

Node HTTP GET request

We can use the HTTP module to create client requests as well.

The example creates an HTTP GET request to the webcode.me .

The options contain the hostname, port, path, and HTTP method of the generated request.

A request is generated with request .

We continuously write incoming data to the console in the data event handler.

Alternatively, we can use the get method.

We generate a GET request to the same website.

We continuously add retrieved chunks of data to the content variable.

In the end, we print the variable to the console.

Node HTTP POST request

The following example creates a POST request to the httpbin.org website. This is a free site where we can test our requests. Since the site uses HTTPS protocol, we use the https module.

The example sends data to the testing website. The server respons with data which includes the payload that we have sent.

We use the https module.

This is the payload to be send.

These are the headers. We send JSON data. We specify the content length.

These are the options of the POST request. The HTTPS stardart port is 443.

In the data event handler of the post call, we write the data to the console.

We write the payload data to the POST request.

The request is sent.

JS HTTP module

In this article we have worked with the JavaScript HTTP module.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all JavaScript tutorials.

  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
  • Print hello world using Express JS
  • Express.js app.locals Property
  • Express.js | app.route() Function
  • Express.js res.type() Function
  • Express app.listen() Function
  • Express.js req.method Property
  • Folder structure for a Node JS project
  • How to Enable HTTPS for Localhost ?
  • Express JS express.json() Function
  • Express.js | app.set() Function
  • Express res.json() Function
  • Express.js | app.param() Function
  • Express.js res.set() Function
  • How to create routes using Express and Postman?
  • Express.js req.ip Property
  • Express.js app.mountpath Property
  • Express.js req.acceptsEncodings() Function
  • Express.js | app.METHOD() Function
  • Express.js res.vary() Function

Difference between res.send() and res.json() in Express.js?

In this article, we will learn about res.send() & res.json(), along with discussing the significant distinction that differentiates between res.send() & res.json().

Let us first understand what is res.send() and res.json() in Express.js?

res.send() – The res.send() function is used for sending the response for the HTTP request. It takes a parameter body. The parameter can be a String, Buffer object, an object, Boolean, or an Array.

Parameter: The body parameter takes a single argument that describes the body that is to be sent in the response.

Content Type: The Express sets the content type of the parameter according to the type of the body parameter.

  • String & HTML – “text/html”
  • Buffer – “application/octet-stream”
  • Array & object – “application/json”

Return Type: It is used to send a response to the client and then ends the response process. The method itself doesn’t return anything.

Example: This example demonstrate the simple res.send().

  • Console output:
  • Browser Output:

ressend

Simple example of res.send()

res.json() – The res.json() function sends the response as JSON format. It automatically converts the JavaScript object into a JSON-formatted string. The parameter body can be of any JSON type, which includes object, array, string, Boolean, number, or null.

res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

Parameter: The body parameter takes JavaScript Object as its argument.

Content Type: Its content-type is set to – “application/json”.

Returns: It is used to send JSON response to the client and then ends the response process.

resjson

Simple example of res.json()

Difference between res.send() and res.json():

Through both res.send() and res.json() seems to identical and fulfill similar purposes but still there is significant contrast that differentiates both res.send() and res.json(), which is given below.

Conclusion:

Both res.send() and res.json() serves similar purposes with some difference. So it depends on the data type which we are working with. Choose res.json() when you are specifically working with JSON data. Use res.send() when you need versatility and control over the content type or when dealing with various data types in your responses.

Please Login to comment...

Similar reads.

  • Web Technologies
  • Google Introduces New AI-powered Vids App
  • Dolly Chaiwala: The Microsoft Windows 12 Brand Ambassador
  • 10 Best Free Remote Desktop apps for Android in 2024
  • 10 Best Free Internet Speed Test apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. How To Read And Write Json Data Using Python 3 Youtube

    res write json

  2. How To Read And Write Json File Using Nodejs Images

    res write json

  3. How to Read and Write JSON File in Python

    res write json

  4. How to write JSON object to File in Java? Simplifying JSON File

    res write json

  5. What is a JSON Array? JSON Array Definition & Examples

    res write json

  6. Tutorial: Query a Database and Write the Data to JSON

    res write json

VIDEO

  1. Main Madine Chala _ New Naat 2024 _ Phir Karam Hogaya _ Owais Raza Qadri _ Azim Write

  2. How To Write Your PhD Research Proposal

  3. Coffee with Nels: E10 using Python to extract knowledge from webpage content and save JSON files

  4. 77 à€•à„‹ à€€à„€à€š à€Źà„‰à€•à„à€ž à€źà„‡à€‚ à€Čà€żà€–à„‹

  5. 10 Cadres Caught

  6. what is mind mapping

COMMENTS

  1. Proper way to return JSON using node or Express

    The one that I have seen commonly being used is by using a command of the form: response.write(JSON.stringify(anObject)); However, this has two points where one could argue as if they were "problems": We are sending a string. Moreover, there is no new line character in the end. Another idea is to use the command:

  2. How To Use the res Object in Express

    app. get ('/home', (req, res) => {res. send ('Hello World!'. Notice that the GET request takes a callback argument with req and res as arguments. You can use the res object within the GET request to send the string Hello World! to the client-side.. The .send() method also defines its own built-in headers natively, depending on the Content-Type and Content-Length of the data.

  3. Express Response JSON

    The res.json() uses JSON.stringify() under the hood to serialize objects into JSON. You can configure the arguments that Express passes to JSON.stringify() using app.use(). For example, to make Express pretty print JSON, you can use app.set('json spaces', 2) as shown below.

  4. The res Object in Express

    The res.json() function converts the given object to JSON using JSON.stringify() and sets the content type to 'application/json; charset=utf-8'. ... There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called ...

  5. res.json() vs res.send() vs res.end() in Express by Tamas Piros

    The answer is two-fold: yes and no. We can use res.end () if we want to end the response without providing any data. This could be useful for a 404 page, for example: res.status(404).end(); In the code above we are explicitly setting the HTTP status code and immediately after that ending the response.

  6. Express res.json() Function

    The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. ... Write and publish your own Article ...

  7. Difference between res.json vs res.send vs res.end in Express.js

    To sum things up, res.json() allows for extra formatting of the JSON data - if this is not required res.send() can also be used to return a response object using Express. Both of these methods ...

  8. Express res.json() Method

    The res.json() method simplifies the process of sending JSON responses to clients. It automatically sets the Content-Type header to application/json and converts the provided JSON object into a string for transmission. res.json(user); }); In this example, the res.json() method is used to send a JSON response containing user information.

  9. What is the difference between res.send and res.write in express?

    17. res.send is equivalent to res.write + res.end So the key difference is res.send can be called only once where as res.write can be called multiple times followed by a res.end. But apart from that res.send is part of Express. It can automatically detect the length of response header.

  10. Express 5.x

    Enable escaping JSON responses from the res.json, res.jsonp, and res.send APIs. This will escape the characters < , > , and & as Unicode escape sequences in JSON. The purpose of this is to assist with mitigating certain types of persistent XSS attacks when clients sniff responses for HTML.

  11. Server-Sent Events with Express

    The res.write() function writes to the HTTP connection without explicitly ending the HTTP response. Make sure you do not use res.send() or res.end() , because those explicitly end the response. Below is an example of a standalone Express server that handles SSE with the /events endpoint:

  12. Response: json() method

    The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON . Note that despite the method being named json(), the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript ...

  13. Difference between response.send and response.write in node js

    res.send() is part of Express.js instead of pure Node.js. Just an side observation. My app sometimes send back a very large Json object ( HighChart object that contains over 100k points). With res.send() sometimes it hangs and choke up the server, whereas res.write() and res.end() handle it just fine.. I also noticed a memory spike when res.send() is invoked.

  14. Node.js response.write() Method

    The response.write() (Added in v0.1.29) method is an inbuilt Application program Interface of the 'http' module which sends a chunk of the response body that is omitted when the request is a HEAD request. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.. The first time response.write() is called ...

  15. 21. Node.js Lessons. Writable Response Stream (res), Pipe ...

    We can already read from the file using ReadStream: 1. var file = new fs.ReadStream('big.html'); It will be an input-data stream. While an output-data stream will be a response object res, which is an object of the http.ServerResponse class that inherits from stream.Writable.

  16. javascript

    Here is an example usage of writing your JSON to a file with Streams. fs.createReadStream() is used to create a readable stream of the stringified docs object. Then that Readable is written to the filepath with a Writable stream that has the Readable data piped into it.

  17. Express 4.x

    Enable escaping JSON responses from the res.json, res.jsonp, and res.send APIs. This will escape the characters <, >, and & as Unicode escape sequences in JSON. The purpose of this it to assist with mitigating certain types of persistent XSS attacks when clients sniff responses for HTML. NOTE: Sub-apps will inherit the value of this setting.

  18. Node HTTP

    res.writeHead(200, { 'Content-Type': 'application/json' }); We inform the client that we send JSON response in the header with the appropriate content type. res.write(JSON.stringify({ now: new Date() })); We write the current date in JSON to the response. Node HTTP send HTML. Next, we are going to send HTML data to the client.

  19. Node Res.write send multiple objects:

    Write is for writing strings to the response body, the parameters accepted are (chunk[, encoding][,callback]), however an object is not a string, and your min/max values are not encodings.. As said before, you could use JSON.stringify to convert an object into a JSON string, however since this is pretty common behaviour Express provides a send method that can do exactly that.

  20. Difference between res.send() and res.json() in Express

    res.json(): res.json() is a function that helps send a response in the form of JSON (JavaScript Object Notation) to the client. When you use this function, it automatically sets the type of content in the response to be JSON and sends the provided JavaScript object as the body of the response. This is particularly useful when your server needs ...

  21. Difference between res.send() and res.json() in Express.js?

    Both res.send () and res.json () serves similar purposes with some difference. So it depends on the data type which we are working with. Choose res.json () when you are specifically working with JSON data. Use res.send () when you need versatility and control over the content type or when dealing with various data types in your responses.