0

I am very lost on how I can send data from server to client. I need the client javascript to access the array in the server, but I have no idea how I can do that.

index.js

var http = require('http')
var fs = require('fs')
let avails = [0, 0, 0];
var url = require('url');
var path = require('path');
var express = require('express');
const app = express();

http.createServer(function (req, res) {
let route = req.url.replace('/', '')

let request_url = route === '' || route === '/' ? 'website.html' : route

var room = url.parse(req.url, true).query['r'];
var status = url.parse(req.url, true).query['f'];

avails[room] = parseInt(status);
console.log(avails);

console.log(request_url)

fs.exists(request_url, (exist) => {
    if (Boolean(exist) === false) {
        res.writeHead(404, {'content-type': 'text/html'})
        res.end('Page Not Found')
        return null
    }

    fs.readFile(request_url, function (err, data) {
        res.writeHead(200)
        res.write(data)
        res.end()
    })
   })
}).listen(8080);

app.post('/data', async (request, response) => {
    const json = JSON.stringify(avails);
    response.json(json);
});

web.html

<!DOCTYPE HTML>
<html>
<head>
    <title>Room Availability Detection System</title>
    <link rel="stylesheet" href="website.css">
</head>
<body>
    <div class="island">
        <div class="title">
            <p >Piano Room Availability</p>
        </div>
        <table id="avail">
            <tr id="rooms">
                <td>Room 1</td>
                <td>Room 2</td>
                <td>Room 3</td>
            </tr>
            <tr id="status">
                <td id="1">Available</td>
                <td id="2">Available</td>
                <td id="3">Available</td>
            </tr>
        </table>
    </div>
    <script src="./website.js"></script>
</body>

If someone can guide me how I can do this, I would greatly appreciate it. Thanks in advance.

0

1 Answer 1

1

Backend

First off, I strongly advise you to read the express docs or some tutorials. I refactored your code. Change the import methods the way you want, I believe you use require.

import express from "express";
import path from "path";
const app = express();

// The backend shouldn't be running 24/7. You should store this data in
// a database (SQL/MongoDB/anything else), or at least in a JSON file.
const avails = Array(3).fill(0);

// Parse JSON bodies for POST requests
app.use(express.json());

// Logger. I advise you to check out "morgan" on npm,
// it's the best-known logger for express:
// app.use(morgan("dev"))
app.use((req, res, next) => {
    console.log(req.path);
    next();
});

// You should move "website.html" to "public/website.html"
// Every file in "public/" will be staticly accessible.
// If I understood correctly, there's other files you want to serve.
// Put them there too.
app.use("/", express.static(path.join(__dirname, "public")));

// Use get, not post! You're not creating data, but fetching data
app.get("/avails", (req, res) => res.json(avails));

// This route is to update the status of a room. Security-wise,
// it isn't very good as the array can be completely destroyed by a 
// remote client, but it works. Example: 
// POST /rooms/2/status { value: 2 }
app.post("/rooms/:room/status", (req, res) => {
    if (typeof req.body["value"] !== "number")
        return res.status(400).json({ message: "No valid new value is specified" });
    const room = +req.params["room"];
    const newStatus = req.body["value"];
    avails[room] = newStatus;
    console.log("new avails:", avails);
    res.json({ message: "Success!", avails });
});

// Connect to port 3000
app.listen(3000, () => console.log("Server is ready"));

Deprecation warnings

Now, a quick note on the things you're using while you shouldn't. I'm adding this because the above code doesn't replace the methods, but avoids them.

  1. Use express properly please, but I think you got it by now:
    • Use the express.static() middleware whenever you can for static files
    • Use middlewares.
    • Use properly the req and res objects. Simplicity is your friend.
  2. url.parse is deprecated, you should use new URL(), and get the search params from its searchParams property.
  3. fs.exists is also deprecated.

Frontend

You can make requests to your backend using the fetch API.

const root = "http://localhost:3000"; // Or whatever your backend URL is

async function getAvails() {
    const url = new URL("/avails", root).href;
    const body = await fetch(url).then(res => res.json());
    return body.data;
}

async function setRoomState(room, value) {
    const url = new URL(`/rooms/${room}/status`, root).href;
    const body = await fetch(url, { method: "POST", body: { value } }).then(res =>
        res.json()
    );
    // Returns new avails
    return body.avails;
}

// Use these functions wherever you want

Side note about your project

If your project is about counting the number of people in a room, maybe you'll want to check out an old (small) project of mine, echo. Here's echo-mum, the backend written in TypeScript, maybe it'll help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.