我的server.js
具有以下功能:
const express = require('express');
const someFunction = () => {
setInterval(() => {
console.log('ok');
}, 1000);
};
app.listen(3001, () => someFunction());
如何从React组件运行此功能?就像我在React中有一个Button组件一样:
<Button onClick={() => express.someFunction(...)}
答案 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)