Javascript Ajax时区服务

Javascript Ajax时区服务,javascript,node.js,ajax,Javascript,Node.js,Ajax,我需要创建一个web服务器,对于X以外的时区,它将当前日期和时间发送到web浏览器(对于每个传入的请求) 服务的URL:http://localhost:8080/time/ 有人能解释一下我应该怎么做吗?您可以在Node.js中创建一个简单的REST服务,并在请求时提供时区列表和时区的当前时间 你得跑了 npm install express moment moment-timezone 安装所需的软件包 使用node index.js启动服务,然后将浏览器指向 您应该会看到时区下拉列表 选

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

服务的URL:
http://localhost:8080/time/


有人能解释一下我应该怎么做吗?

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

你得跑了

npm install express moment moment-timezone
安装所需的软件包

使用node index.js启动服务,然后将浏览器指向

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

选择时区将显示该时区中的当前时间

您还可以使用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}`);
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);
然后创建一个/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 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}`);
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);
const dropdown=document.getElementById('timezone-dropdown');
常量getTimeInterval=1000;//1000毫秒。
const selectedTimezone=“美国/洛杉矶”;
异步函数getTimezoneList(){
let response=wait fetch('/timezones');
让timezoneList=wait response.json();
timezoneList.forEach(时区=>{
让option=document.createElement('option');
option.text=时区;
option.value=时区;
下拉列表。添加(选项);
});
//设置所选时区
dropdown.selectedIndex=timezoneList.findIndex(时区=>timezone===selectedTimezone);
}
异步函数getTimezoneTime(时区){
let response=wait fetch(“/time”{
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
方法:“张贴”,
正文:JSON.stringify({timezone})
});
让timeDetails=wait response.json();
log(“getTimezoneTime:response:”,timeDetails);
return timeDetails.currentTime;
}
异步函数GetCurrentTimeorSelectedTimeZone(){
log(“获取时间”+下拉列表.value);
常量时间=等待getTimezoneTime(dropdown.value);
document.getElementById('output').innerHTML=`当前时间:${time}`
}
getTimezoneList();
//每秒读取当前时间。
setInterval(GetCurrentTimeorSelectedTimeZone,getTimeInterval);

请详细描述您想要什么、您尝试了什么、出了什么问题等。首先,定义
X
是什么,因为这里的问题太模糊了。然后描述“当前日期和时间”的含义,即是服务器时区还是客户端时区。然后,描述您将要使用的服务器端语言,因为还不清楚,因为您自己没有尝试过这样做