【问题标题】:Is there a way to have a GET request with setInterval on the backend without the help of the client side/frontend?有没有办法在没有客户端/前端帮助的情况下在后端有一个带有 setInterval 的 GET 请求?
【发布时间】:2020-06-28 08:31:58
【问题描述】:

我有这个从第三方 api 获取数据的 GET 请求。我想每隔 5-10 分钟左右检查一次是否有新数据。现在我的后端有这个设置。

exports.get_alerts = async (req, res) => {
  const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?cpo=${req.params.cpo}&status=Opened&limit=10&page=1`;
  const axios = require("axios");
  const auth = await refreshToken;
  const currTime = moment().subtract(1, "days").format("X");
  const newAlertsData = [];

  const availableUsers = await axios.get(
    "http://localhost:5000/api/schedule/available"
  ) ....

在前端我有这个代码来向我的警报 api 端点发送一个获取请求。

 getAlerts = async () => {
    axios
      .get("/api/alerts/total_fr_hpc")
      .then((response) => console.log(response.data))
      .catch((err) => console.log(err));
  };

  timer = (time) => {
    const date = new Date(time);
    return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  };

  componentDidMount() {
    this.alertsInterval = setInterval(this.getAlerts, 900000);
  }

  componentWillUnmount() {
    clearInterval(this.alertsInterval);

我的问题是我可以只在后端完成所有这些吗?我读了一些关于 websockets 的文章,但这似乎只是为了后端和前端之间的连续 2way 连接。

我想在节点/快递服务器上对我的第三方 api 有类似的东西,要么以设定的时间间隔获取数据,要么连续连接检查新数据,而不必从我的前端发出 GET 请求。即使没有人登录到客户端,我也希望能够获取新数据并将其存储到 MongoDB。

我希望用户获得的数据始终是最新的,而无需至少一个人登录来触发 GET 请求。

这就是我的 node/express 服务器当前的设置方式

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const path = require("path");


const indexRouter = require("./routes/index");
const apiRouter = require("./routes/api"); //Import routes for "api" area of site

const app = express();

// CORS Middleware

app.use(cors());
app.options("*", cors());
// Bodyparser middleware
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
app.use(bodyParser.json());

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() => console.log("MongoDB successfully connected"))
  .catch((err) => console.log(err));

// Passport middleware
app.use(passport.initialize());

// Passport config
require("./config/passport")(passport);

// Routes
// Add api routes to middleware chain.
app.use("/", indexRouter);
app.use("/api", apiRouter);

// Serve static assets (build folder) if in production
if (process.env.NODE_ENV === "production") {
  // Set static folder
  app.use(express.static("client/build"));

  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

const port = process.env.PORT || 5000;

app.listen(port, "0.0.0.0", () =>
  console.log(`Server up and running on port ${port} !`)
);

【问题讨论】:

    标签: javascript node.js express websocket server-sent-events


    【解决方案1】:

    我不熟悉 axios,因为我总是使用原生 fetch API。也许the isomorphic fetch 可以提供帮助。

    【讨论】:

    • fetch 和 axios 做同样的事情。那不是我的问题。我想从后端在 setInterval 处执行这些请求,而不是从前端触发它。
    • 要在节点而不是浏览器中使用 fetch,请使用 node-fetch。当浏览器代码和节点代码都存在于同一个项目中时,我建议使用isomorphic unfetch
    猜你喜欢
    • 2014-05-11
    • 2016-07-04
    • 2021-09-19
    • 1970-01-01
    • 2021-12-28
    • 2019-11-11
    • 1970-01-01
    • 2021-07-14
    • 2017-05-10
    相关资源
    最近更新 更多