EN
Express.js - send response with status
3 points
In this article, we would like to show you how to send response with status using Express.js.
Quick solution:
xxxxxxxxxx
1
response.sendStatus(200); // sends 200 status code with empty response
or:
xxxxxxxxxx
1
response.status(200).send('Response message!');
Where: send()
method can be replaced by any method from response API.
In this section you can find most common methods used in response API.
Method | Description |
send() | Sends indicated data as response, e.g. 'Response message!' . |
json() | Sends the object as JSON. |
jsonp() | Sends the object as JSONP. |
download() | Transfers the file as "attachment". |
sendFile() | Transfers the file as response content, e.g. index.html . |
etc. | Other methods are available here. |
In this example, we present how to use status()
and json()
methods to send JSON response with status 200
on HTTP GET request.
xxxxxxxxxx
1
const express = require('express'); // npm install express
2
3
const app = express();
4
5
app.get('/path/to/api', (request, response) => {
6
const object = {
7
message: 'Response message!'
8
};
9
response.status(200) // sets success as status
10
.json(object); // sends object as response
11
});
12
13
app.listen(8080, () => console.log('Server started on port 8080.'));