代码之家  ›  专栏  ›  技术社区  ›  Ralph David Abernathy

如何从React app在ExpressJS中执行函数?

  •  1
  • Ralph David Abernathy  · 技术社区  · 6 年前

    我的电脑里有以下功能 server.js

    const express = require('express');
    
    const someFunction = () => {
      setInterval(() => {
        console.log('ok');
      }, 1000);
    };
    
    app.listen(3001, () => someFunction());
    

    如何从React组件运行此函数?就像我在React中有一个按钮组件:

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Evans    6 年前

    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)