Search code examples
javascriptnode.jsexpressserverhttp-method

How to access req.body via expressjs?


I cant access body when getting expressjs request

My main server.js file

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

My router.js file

const express = require("express");
const articlesContr = require("./../controllers/articlesContr.js");
const router = express.Router();

router
  .get("/articles", articlesContr.handleGet)
  .post("/articles", articlesContr.handlePost)
  .put("/articles", articlesContr.handleUpdate)
  .delete("/articles", articlesContr.handleDelete);

adminPanelContr.js

const controller = {
    handleGet: (req, res) => {
        const query = req._parsedUrl.query;
        const parsedQuery = querystring.parse(query);
        // res.send(productsDb.getItem(parsedQuery));
        console.log(req)
        res.send(JSON.stringify(req.body))
    }
};

Solution

  • GET requests don't have body parameters. Ordinarily .get() handler functions don't look for them.

    If you use the same handler function for GET and other (POST, PUT, PATCH, DELETE) requests, you need logic to avoid looking at the body when you get a GET.

    When you send a request with a JSON body, don't forget to tell your server it's JSON by including a Content-Type: application/json HTTP header. That way you're sure express will invoke its express.json middleware to parse the body into the req.body object.

    When you .get() a GET, you don't get a request body. There's gotta be some sort of doggerel poetry in there someplace.

    If you use res.json(object) rather than res.send(JSON.stringify(object)) express does a good job of setting the HTTP response headers to useful values for JSON.

    And, I'm sure you know this: Responding to a request with its own request body is a little strange.