将数组从服务器发送到客户端 NodeJs

时间:2021-04-18 08:35:06

标签: node.js http

我对如何从服务器向客户端发送数据感到非常困惑。我需要客户端 javascript 来访问服务器中的数组,但我不知道如何做到这一点。

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>

如果有人能指导我如何做到这一点,我将不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:1)

后端

首先,我强烈建议您阅读express docs或一些教程。我重构了你的代码。按照您想要的方式更改导入方法,我相信您会使用 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"));

弃用警告

现在,快速记录一下您不应该使用的东西。我添加这个是因为上面的代码没有替换方法,而是避免了它们。

  1. 请正确使用快递,但我想您现在已经明白了:
    • 对静态文件尽可能使用 express.static() 中间件
    • 使用中间件。
    • 正确使用 reqres 对象。简单是你的朋友。
  2. url.parse 已弃用,您应该使用 new URL(),并从其 searchParams 属性中获取搜索参数。
  3. fs.exists 也已弃用。

前端

您可以使用 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

关于您的项目的旁注

如果你的项目是关于计算一个房间里的人数,也许你会想看看我的一个旧的(小)项目,echo。这是用 TypeScript 编写的后端 echo-mum,也许它会有所帮助。