我的 server.js
中有以下功能:
const express = require('express');
const someFunction = () => {
setInterval(() => {
console.log('ok');
}, 1000);
};
app.listen(3001, () => someFunction());
如何从 React 组件运行此函数?就像我在 React 中有一个 Button 组件一样:
<Button onClick={() => express.someFunction(...)}
最佳答案
您需要创建一个调用该函数的快速端点。 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')
})
然后你可以在 React 中使用 fetch api (或 axios )请求该资源,如:fetch(someUrlThatInvokesFunctionGoesHere)
关于javascript - 如何从 React 应用程序在 ExpressJS 中执行功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51029831/