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

342
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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