【问题标题】:Passing a variable from ReactJS frontend to NodeJS back end using a GET route使用 GET 路由将变量从 ReactJS 前端传递到 NodeJS 后端
【发布时间】:2020-01-21 03:02:03
【问题描述】:

我正在开发一个 react 应用程序,并试图找到一种方法将我在前端 (Question.js) 中定义的变量传递给我的后端 (server.js),以便我可以发出不同的查询.我有代码

//Question.js

state = {
        data: null
    };

    componentDidMount() {
        this.callBackendAPI()
            .then(res => this.setState({ data: res.express }))
            .catch(err => console.log(err));
    }

    callBackendAPI = async () => {
        const response = await fetch('/express_backend');
        const body = await response.json();

        if (response.status !== 200) {
            throw Error(body.message)
        }
        return body;
    };
//server.js

con.connect(function (err) {
    if (err) throw err;
    con.query("SELECT question FROM s1questions WHERE ID = 1", function (err, result, fields) {
        if (err) throw err;
        app.get('/express_backend', (req, res) => {
            var x = JSON.stringify(result[0].question);
            res.send({ express: `${x}` });
        });
    });
});

【问题讨论】:

  • 您的路由处理程序可能不应该在您的数据库连接回调中定义另外,您使用的数据库包是什么?您需要使用参数化查询来检索您的问题

标签: javascript sql node.js reactjs


【解决方案1】:

您的服务器可能应该将您的数据库连接与您的路由处理程序定义分开。此外,您可以使用查询参数根据数据库中的 id 访问问题。

// question.js
    callBackendAPI = async () => {
        const response = await fetch(`/express_backend?questionId=1`);
        const body = await response.json();

        if (response.status !== 200) {
            throw Error(body.message)
        }
        return body;
    };

// server.js
app.get('/express_backend', (req, res) => {
  const { questionId } = req.query;

  // query database for question by id
});

【讨论】:

  • @coldcav 如果您觉得有帮助,请接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2020-12-25
  • 2016-06-12
  • 2020-12-18
  • 2016-12-29
相关资源
最近更新 更多