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);
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 });
}