1

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.

Seybsen
  • 14,989
  • 4
  • 40
  • 73
Vinicius Mocci
  • 99
  • 3
  • 12

1 Answers1

1

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'
Seybsen
  • 14,989
  • 4
  • 40
  • 73
  • I've tried with Postman (urlencoded) and curl, both worked, tks! But one last question: does a simple web post form will work out like this too? – Vinicius Mocci Jul 16 '20 at 11:23
  • Depends on your form. If you use `
    ` it's `x-www-form-urlencoded`, but if you use `
    ` it will use `multipart/form-data` and allow file uploads. See https://stackoverflow.com/a/4526286/982002 for more info.
    – Seybsen Jul 16 '20 at 11:29