0

I am trying to run a send mail test using vanilla js and Node.js.

Everything works fine with node but whenever I send a post request using fetch to Node.js server, req.body returns undefined. I have tried using body-parser, cors, and express.json() but still the same thing

// node.js
const express = require('express');
const cors = require('cors');
// const bodyparser = require('body-parser');

const app = express();

// MIDDLEWARE  
app.use(express.urlencoded({
  extended: true
}))
app.use(express.json());
app.use(cors());

app.post('/api/sendemail', (req, res) => {
  const { email } = req.body;
  console.log(email);
  res.status(200).json('Email sent');
}
// Vanilla js
const mailsend = (data) => {
  return fetch('http://localhost:5000/api/sendemail', {
      method: "POST",
      body: JSON.stringify(data)
    })
    .then(response => {
      return response.json();
    })
}

const sending = async() => {
  const post = {
    title: "Test",
    body: 'Howdy there, how is it going',
    userID: Math.random()
  }
  const data = await mailsend(post);
  console.log(data);
}

sending();
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132

0 Answers0