expressjsHow do I create a REST API with Express.js?
Creating a REST API with Express.js is relatively simple. The following example code shows how to create a basic API with two endpoints: GET /hello
and POST /hello
.
const express = require('express')
const app = express()
app.get('/hello', (req, res) => {
res.send('Hello World!')
})
app.post('/hello', (req, res) => {
res.send('You just called the post method at "/hello"')
})
app.listen(3000)
The code above will create an Express.js server listening on port 3000. When a GET
request is sent to /hello
, it will respond with Hello World!
and when a POST
request is sent to /hello
, it will respond with You just called the post method at "/hello"
.
The code above includes the following parts:
const express = require('express')
: This imports the Express.js module.const app = express()
: This creates an Express.js application.app.get('/hello', (req, res) => {...})
: This creates aGET
endpoint at/hello
.app.post('/hello', (req, res) => {...})
: This creates aPOST
endpoint at/hello
.app.listen(3000)
: This starts the server and makes it listen on port 3000.
For more information on creating a REST API with Express.js, see the following links:
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I use Express.js to create a YouTube clone?
- How do I manage user roles in Express.js?
- How can I use Express.js to develop a web application?
- How can I disable the X-Powered-By header in Express.js?
- How can I use Express.js and websockets together to create real-time applications?
- How can I use express-zip js to zip and download files?
- How can I use Express.js and Winston together to create a logging system?
- How do I set the time zone in Express.js?
- How can I use the x-forwarded-for header in Express.js?
See more codes...