jsldnppl
jsldnppl

Reputation: 913

Node POST request - receive data

I'm trying to make a POST request to my node/express server, to send an email. I would like to pass through the details of the email via the request, but am not able to get the data on the node side.

This is what I've got so far note: the email send part is psuendo code

index.js

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
const response = await fetch('/api/hello', {
  method: 'post',
  body: jsonDataObj
});

server.js

const express = require('express');
const app = express();
const bodyParser = require("body-parser");

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

app.post('/api/hello', (req, res) => {

  const msg = {
    to: req.body.to,
    subject: req.body.subject,
    text: req.body.text
  };

  sendEmail(msg);
});

app.listen();

Upvotes: 0

Views: 113

Answers (1)

Quentin
Quentin

Reputation: 943097

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};

That is a JavaScript object, not JSON.

When you pass it to fetch, it will be converted to a string by calling its toString() method.

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
console.log(jsonDataObj.toString());

This:

  • is not JSON
  • is not url encoded
  • doesn't actually contain any of your data

You need to encode the data in a format that can be sent over HTTP.

For example, this will sent in multipart format:

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = new FormData();
Object.keys(jsonDataObj).forEach(key => data.append(key, jsonDataObj[key]));
const response = fetch('/api/hello', {
  method: 'post',
  body: data
});

… which you can read with multer.

While this will encode using a query string which bodyParser.urlencoded should be able to handle.

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = new URLSearchParams();
Object.keys(jsonDataObj).forEach(key => data.append(key, jsonDataObj[key]));
const response = fetch('/api/hello', {
  method: 'post',
  body: data,
  headers: { "Content-Type": "application/x-www-form-urlencoded" }
});

And this will actually use JSON:

var jsonDataObj = {'to': 'example@exmpale', 'subject': 'this is the subject','text': 'this is the text',};
var data = JSON.stringify(jsonDataObj);
const response = fetch('/api/hello', {
  method: 'post',
  body: data,
  headers: { "Content-Type": "application/json" }
});

Upvotes: 4

Related Questions