如何从React应用程序在ExpressJS中执行功能?

时间:2018-06-25 18:29:33

标签: javascript reactjs express server server-side

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

const express = require('express');

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

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

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

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

1 个答案:

答案 0 :(得分:2)

您将需要创建一个调用该函数的明确端点。 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)