0

I am able to retrieve(get) data from express but cannot post data to express...

client:

<html>
  <button onclick="myFunction()">send</button>
  <script>
    const data = {"experience" : 0};
    function myFunction(){
      fetch("/post", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
    }
  </script>
</html>

express:

Here I was getting undefined, but when I added express.json(), I got "{}". The client's and the server's conections are good, but there is no body where the data is stored? I made sure my client code was working fine by posting data to webhooks.site, it worked fine. I think there is some kind of rookie mistake... Btw, I am using react and express, I just simplified my code... any suggestions will be appreciated

const express = require("express");
const app = express();

app.post("/post", express.json() ,function (req,res){
  console.log(req.body)
})

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

imback0526
  • 164
  • 2
  • 9
  • 2
    `onclick="function myFunction()"` --> `onclick="myFunction()"`. Currently I believe you are only redefining (overwriting) `myFunction` with another, void one. Also, you don't need `JSON.stringify`. Just send `body:data` – Jeremy Thille Sep 01 '21 at 14:36
  • The request is sent to the server from client. Server received request but the request.body is missing? – imback0526 Sep 01 '21 at 16:40
  • Are you using Express 4.16+? The prior one didn't have built in body parser. – digitalniweb Sep 01 '21 at 16:49
  • check your Console tab in Chrome Developer tools to make sure there are no errors. – Amin Cheloh Sep 01 '21 at 16:57

1 Answers1

0

I have had to use Body Parser (simple) or Busboy (advanced) to access data in POST body with Express.

An example might look like:

const bodyParser = require('body-parser');

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

app.post("/post",(req,res,next)=>{
  console.log(req.body);
})
outlaw
  • 197
  • 8
  • Body-parser was [deprecated](https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4) a long time ago, since [Express 4.16 in September 2017](https://expressjs.com/en/changelog/4x.html#4.16.0). Now use `app.use(express.json())` instead. – Jeremy Thille Sep 02 '21 at 06:24