I'm trying to retrieve body data but I only receive undefined on my terminal, dunno how/where to retrieve the "email". I've googled it a bit but can't seen to find the answer.
Here's the app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
//routes which should handle request
app.post("/orders", (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
And here's the server.js file:
const http = require('http');
//import app.js file
const app = require('./app');
//define port to be used
const port = process.env.PORT || 3100;
const server = http.createServer(app);
server.listen(port, () =>{
//print a message when the server runs successfully
console.log("Success connecting to server!");
});
I want to receive the "name" data and use it in a function to return a json. I'm using postman to send post requests with one key only, named "email". Postman receives the Json test data "Orange, Apple, Banana" that I have coded, though.
For x-www-form-urlencoded
your example should work fine (just choose it in Postman under the body tab).
If you want to POST data (e.g. with files) as multipart/form-data
you can install the multer middleware and use it in your app: app.use(multer().array())
// File: app.js
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer().array());
//routes which should handle request
app.post("/orders", async (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
This works with:
curl --location --request POST 'localhost:3100/orders' \
--form 'email=john@example.com'
and
curl --location --request POST 'localhost:3100/orders' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'email=john@example.com'