Best practice with HTTP verbs and nodeJS/Express?

Viewed 326

I am new to developing, and am setting up a express/node app. I am getting confused with best practices around HTTP verbs and when I use each one. I know with REST API's the rules are to use POST to create new resources, GET to display, etc. So you would have the same link address (/articles in this example) to send those requests like this:

app.route("/articles")
  .get((req,res)=>{
     // send an article to client
   }
  .post((req,res)=>{
     // send a new article back to server
   }

The original version of my node app had only get and post requests (since that's all html forms support) with different link addresses to be clearer about what was happening:

  app.get("/articles/article-1", (req,res)=>{
     // send an article to client
   }
  app.post("/articles/new", (req,res)=>{
     // send a new article back to server
   }
  app.post("/articles/article-1/update", (req,res)=>{
     // update an article
   }

I have since found the method-override npm package so I updated my node app to include the different HTTP verbs like this:

  app.get("/articles/article-1", (req,res)=>{
     // send an article to client
   }
  app.post("/articles/new", (req,res)=>{
     // send a new article back to server
   }
  app.patch("/articles/article-1/update", (req,res)=>{
     // update an article
   }

So the first question is is it standard practice in nodejs websites to be using only GET and POST requests with forms and changing the link addresses (/new, /save) to match what is happening? (so PUT, PATCH and DELETE are used with REST APIs specifically?) Or are you meant to use plugins like method-override?

And second, if you are meant to use method-override, is it better to use many different link addresses that tell you more about what's actually happening (/new, /save), or trying to be concise in re-using the same addresses to send the requests through like in a REST API (like the first code example).

1 Answers

"/articles/new" or "/articles/article-1/update" are incorrect naming. When you use POST method to /articles endpoint, you already be say "i want to create new user". So you shouldn't write it again in endpoint. So correct way is:

POST -> /articles --> create new article
GET  -> /articles --> get articles
DELETE -> /articles/1 --> delete article which id is equal 1
UPDATE -> /articles/1 --> update article which id is equal 1 (for lots of  changes in article fields)
PATCH -> /articles/1 --> update article which id is equal 1 (for little of changes in article fields)

Note : If you use SSR in your web application you can append article titles for get method in order to increase SEO performance of website.

Related