Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

74
Vistas
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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda