1

In the code snippet below, do I need to use the urlencodedParser like I do in Post methods.

app.put('/api/provider/:id', urlencodedParser, function (req, res) {

}
Coder1234
  • 389
  • 1
  • 3
  • 9

1 Answers1

2

body-parser parses the body of the request into req.body, which you'll likely need for your put middleware. body-parser now comes built into Express (as of v4.16.0 - below assumes you have an updated version).

The easiest implementation is to use express.json and express.urlencoded (used in body-parser) in all requests, using app.use, so that you don't have to worry about it in your middleware. Here is how npx express-generator $APP_NAME will set it up for you:

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

NOTE: You'll need to set extended to true if you are expecting nested objects in your requests.

JBallin
  • 8,481
  • 4
  • 46
  • 51
  • So if I set them both up I don't have to add in urlencodedParser to my put function. If I wanted it to just use JSON parser would I just need to use app.use(express.json());. In Postman if I use JSON do I just send a post or put using raw. – Coder1234 Mar 19 '19 at 09:03
  • 1) If you put those two lines toward the top of your app.js, you won't need to worry about bodyparser at all in any of your routes. 2) You don't want to use urlencoded? why? 3) Yes, in Postman you can test put/post by putting JSON in raw and setting the type to "JSON (application/json)" Let me know how else I can help. – JBallin Mar 19 '19 at 22:37