javascript - Ajax 时区服务
问题描述
我需要创建一个 Web 服务器,对于 以外的时区X
,将当前日期和时间发送到 Web 浏览器(对于每个传入请求)
服务网址:http://localhost:8080/time/
有人可以解释我应该怎么做吗?
解决方案
您可以使用Moment和Moment 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);
推荐阅读
- azure - Azure 耐用功能扇出扇入建议
- javascript - 当第三方库触发事件时,如何告诉 React 组件更改其状态?
- json - Flutter - 解码json时出现意外字符
- javascript - 添加 jQuery 以作用于动态创建的 Select/Option
- asp.net-core - 在 .NET Core 2.2 的“Microsoft.AspNetCore.App”中找不到“SignalR”?
- react-native - React-Native Undefined 不是对象(评估 this.props.navigator.push')
- python - Tensorflow 2 中的 tensorflow.contrib.predictor.from_saved_model()
- highcharts - 高图表中 x 轴的数据,时间块为 15 分钟
- javascript - JSON.parse(JSON.stringify(obj)) 如何深度克隆一个对象?
- android-studio - 如何在部分匹配“名称”的文件中搜索字符串