Tommie Jones
Tommie Jones

Reputation: 1011

Not receiving post data on node.js

I have a very simple node.js server:

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

app.post("/searcharea", (req, res, next) => {
  console.log("SEARCH AREA2");
  console.log(req.body);
  res.status(200).send({ok:true});
});

app.listen(3000, () => {
  console.log("Server running on port 3000")
});

However when I use curl and send data to the server I get an undefined as the req.body. Here is my curl statement when testing.

curl --header "Content-Type: application/json"
     --request POST   
     --data '{"username":"search":"here"}' 
     http://localhost:3000/searcharea

Any guidance would be appreciated.

Upvotes: 1

Views: 915

Answers (2)

LMulvey
LMulvey

Reputation: 1670

By default, req.body will be undefined. You need to include some sort of middleware to parse the incoming body of the POST request. Express.js packages this with it in v4.x and above. The included one handles most POST bodies but does not handle multipart requests. You'll need something like multer for that Change your code to this:

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

// parse JSON request body
app.use(express.json());

app.post("/searcharea", (req, res, next) => {
  console.log("SEARCH AREA2");
  console.log(req.body);
  res.status(200).send({ok:true});
});

app.listen(3000, () => {
  console.log("Server running on port 3000")
});

Upvotes: 1

Twiggeh
Twiggeh

Reputation: 1160

I am not sure about this data structure : '{"username":"search":"here"}', but to ingest json data from an express server you are required to use the json middleware like this

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

//!Important
app.use(express.json());

app.post("/searcharea", (req, res, next) => {
  console.log("SEARCH AREA2");
  console.log(req.body);
  res.status(200).send({ok:true});
});

app.listen(3000, () => {
  console.log("Server running on port 3000")
});

Upvotes: 3

Related Questions