【问题标题】:How to execute function within ExpressJS from React app?如何从 React 应用程序中执行 ExpressJS 中的功能?
【发布时间】:2018-12-04 09:42:26
【问题描述】:

我的server.js 中有以下功能:

const express = require('express');

const someFunction = () => {
  setInterval(() => {
    console.log('ok');
  }, 1000);
};

app.listen(3001, () => someFunction());

如何从 React 组件运行此功能?就像我在 React 中有一个 Button 组件:

<Button onClick={() => express.someFunction(...)}

【问题讨论】:

  • 你在客户端/浏览器上使用 React 吗?然后你必须使用 fetch 来调用 Express 服务器。
  • 是的,我看过很多关于如何从 express 服务器获取数据的教程,但没有看到如何从 express 中调用函数。我试图弄清楚即使在浏览器关闭时,在客户端调用的 setTimeout 函数如何持续存在。我假设我可以利用 ExpressJS 来实现这一点。
  • 应该和从服务器获取数据没什么区别。只是调用一个函数而不是获取一些数据。

标签: javascript reactjs express server server-side


【解决方案1】:

您需要创建一个调用该函数的快速端点。 Learn more about express routing.

var express = require('express')
var app = express()

const someFunction = () => {
  setInterval(() => {
    console.log('ok');
  }, 1000);
};


// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  someFunction()
  res.send('hello world')
})

然后从反应中,您可以使用fetch api(或axios)请求该资源,例如:fetch(someUrlThatInvokesFunctionGoesHere)

【讨论】:

    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2011-03-14
    • 2020-06-12
    • 2017-07-31
    • 2021-07-31
    • 2011-08-17
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多