首页 > 解决方案 > Ajax 时区服务

问题描述

我需要创建一个 Web 服务器,对于 以外的时区X,将当前日期和时间发送到 Web 浏览器(对于每个传入请求)

服务网址:http://localhost:8080/time/

有人可以解释我应该怎么做吗?

标签: javascriptnode.jsajax

解决方案


您可以使用MomentMoment Timezone在 Node.js 中创建一个简单的 REST 服务,以在请求时提供时区列表和时区的当前时间。

你需要运行

npm install express moment moment-timezone

安装所需的软件包。

使用节点 index.js 启动服务,然后将浏览器指向http://localhost:8080/

您应该会看到一个时区下拉列表。

选择一个时区将显示该时区的当前时间。

您还可以使用 curl 测试服务:

curl http://localhost:8080/time -X POST -d "{\"timezone\":\"US/Pacific\"}" -H "content-type: application/json"

index.js

const express = require("express");
const port = 8080;
const app = express();
const bodyParser = require('body-parser');
const moment = require("moment");
const momentTimezone = require("moment-timezone");

app.use(express.static("./public"));
app.use(bodyParser.json());

app.get('/timezones', async (req, res) => {
    res.json(moment.tz.names());
})

app.post('/time', async (req, res) => {
    try {
        console.log("/time:", req.body.timezone)
        const timezone = req.body.timezone;
        res.json({ currentTime: moment().tz(timezone).format("YYYY-MM-DD HH:mm:ss") });
    } catch (e) {
        console.log(e);
    }
});

app.listen(port);
console.log(`Serving at http://localhost:${port}`);

然后创建一个/public目录并创建

/public/index.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="margin:50px">
  <h2>Select a timezone</h2>
  <select id="timezone-dropdown" name="timezone">
  </select>
  <p id="output">Output</p>
  <script src="app.js"></script>
</body>
</html>

/public/app.js

const dropdown = document.getElementById('timezone-dropdown');
const getTimeInterval = 1000; // 1000 milliseconds.
const selectedTimezone = "America/Los_Angeles";

async function getTimezoneList() {
    let response = await fetch('/timezones'); 
    let timezoneList = await response.json();
    timezoneList.forEach(timezone => {
        let option = document.createElement('option');
        option.text = timezone;
        option.value = timezone;
        dropdown.add(option);
    });

    // Set the selected timezone
    dropdown.selectedIndex = timezoneList.findIndex(timezone => timezone === selectedTimezone);
}

async function getTimezoneTime(timezone) {
    let response = await fetch("/time", {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify({ timezone })
    });
    let timeDetails = await response.json();
    console.log("getTimezoneTime: response: ", timeDetails);
    return timeDetails.currentTime;
}

async function getCurrentTimeForSelectedTimezone() {
    console.log("Getting time for " + dropdown.value);
    const time = await getTimezoneTime(dropdown.value);
    document.getElementById('output').innerHTML = `<b>Current time: ${time}</b>`
}

getTimezoneList();

// Read the current time every second.
setInterval(getCurrentTimeForSelectedTimezone, getTimeInterval);

推荐阅读