Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

73
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda