Friday, May 28, 2021

pass data using request body

 For get calls, you can pass insecure data using the request parameters, as part of URL itself.

And can fetch them using req.params and req.query for optional params.


But for secure data, we need to use POST and can get the data using request body.

You can use the same request body for get also if they are not passed in url as parameters.

To support req.body use 

app.use(express.json()); --> middleware used by request processing pipeline


With same url we can change multiple methods as different routes.

For post instead of get, change the method in the postman/api client.

const express = require("express");

const app = express();

app.use(express.json);

const courses = [
  { id: 1name: "uday1" },
  { id: 2name: "uday2" },
  { id: 3name: "uday3" },
  { id: 4name: "uday4" },
];

app.get("/api/courses", (reqres=> {
  res.send(courses);
});

app.post("/api/courses", (reqres=> {
  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  courses.push(course);
  res.send(course);
});

app.listen(3000, () => console.log("listening"));
const port = process.env.PORT || 3000;

No comments:

Post a Comment