'POST data passed from frontend JS to Nodejs/Expressjs is always undefined

I have a frontend JS script that takes text input from an HTML text box and sends it to an expressjs server. The body of the POST request, though, is always undefined, or depending on how I tweak things, returning as "{ }" if I view it via console.log( ). As I'm new to this, I can't seem to see what's going wrong.

Front end js:

async function submitCity(){
    let x = document.getElementById("wg_input").value;
    console.log("Successfully captured city name:", x);
    let toWeather = JSON.stringify(x);
    console.log("Input data successfully converted to JSON string:", toWeather);
    
    const options = {
        method: 'POST',
        mode: 'cors',
        headers: {'Content-Type': 'text/plain'},
        body: toWeather
    }

    fetch('http://localhost:3000', options)
    .then(res => console.log(res))
    .catch(error => console.log(error))
}

Backend:

// Dependencies

const express = require('express');
const bp = require("body-parser");
const request = require("request");
const jimp = require('jimp');
const cors = require('cors');
const wgServer = express();
const port = 3000;

// Dotenv package

require("dotenv").config();

// OpenWeatherMap API_KEY

const apiKey = `${process.env.API_KEY}`;

// Basic server initialization

wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))

wgServer.listen(port, function() {
  console.log(`Example app listening on port ${port}!`)
});

wgServer.post('/', async function (req, res) {
  res.set('Content-Type', 'text/plain');
  console.log(req.body)
  res.send('Hello World');
  //const data = await req.body;
  // let jsonData = JSON.stringify(req.body);
 // res.status(201);
  //res.json();
});

The returned data is supposed to be a string of about 15 characters, give or take a few (a city and state). I thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source