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

343
Visualizações
How to pass variable from webpage javascript to node JS

I have a variable in Javascript that I'm trying to pass to node js so that it can be put in a JSON file but it is not writing to the file. I think have made a mistake in either the AJAX Post request or in the node JS routing.

The javascript running on a HTML page

   function WriteToJSON() {
    var floors = document.getElementById("floor-number").value;
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/getfloors",
        dataType :"text",
        data: {Floors: floors},
    })
    }

The Node JS

var http = require('http');
var fs = require('fs');
var url = require('url');
const path = require('path');
var express = require('express');
var serveStatic = require('serve-static');
const { Router } = require('express');
const app = express();
var bodyParser = require('body-parser')
const port = process.env.PORT || 8080;

 app.get("/", function(req, res) {
   res.sendFile(path.join(__dirname, '/welcome-page.html'))
 })

 app.get("/Question-1", function(req, res) {
  res.sendFile(path.join(__dirname, '/Question-1.html'))
})

app.post("/getfloors", (req, res) => {
  var floors = req.body.Floors;
  console.log(floors);
  fs.writeFileSync('Data.json', floors);
})

app.listen(8080);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Is there a reason why you are using AJAX instead of the fetch method?

Try this solution (note, that I've used async function):

async function WriteToJSON() {
    const floors = document.getElementById("floor-number").value;

    const body = new URLSearchParams();
    body.append("Floors", floors);
    
    const response = await fetch('http://localhost:8080/getfloors', { method: 'POST', body });
}
about 4 years ago · Juan Pablo Isaza Relatório
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