ExpressJS - HTTP Methods



The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table lists the most used HTTP methods −

S.No. Method & Description
1

GET

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.

2

POST

The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI.

3

PUT

The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one.

4

DELETE

The DELETE method requests that the server delete the specified resource.

These are the most common HTTP methods. To learn more about the methods, visit http://www.tutorialspoint.com/http/http_methods.htm.

Example

Create a new file called index.js in hello-world directory and type the following in it.

index.js

var express = require('express');
var app = express();

app.get('/', function(req, res){
   res.send("GET Request!");
});

app.post('/', function(req, res){
   res.send("POST Request!");
});

app.put('/', function(req, res){
   res.send("PUT Request!");
});

app.delete('/', function(req, res){
   res.send("DELETE Request!");
});

app.listen(3000);

Save the file, go to your terminal and type the following.

E:\Dev\hello-world>nodemon index.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`

This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot.

GET Request

To test other requests, open postman. Now hit the below URL's in POSTMAN application and you can see the output−

POST Request http://localhost:3000/

POST request

Similary you can test the other urls.

PUT Request http://localhost:3000/

PUT request

DELETE Request http://localhost:3000/

DELETE request
Advertisements