0

I am working on a react app and am trying to find a way to pass a variable I define in my front-end (Question.js) to my back-end (server.js) so that I can issue different queries. I have the code

//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}` });
        });
    });
});
1
  • Your route handler probably shouldn't be defined within your database connection callback Also, what is the database package that you're using? You'll want to use parameterized queries in order to retrieve your questions Commented Jan 21, 2020 at 3:22

1 Answer 1

1

Your sever should probably split your database connection from your route handler definitions. Also, you could use query parameters to access questions based on their id in the database.

// 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
});
Sign up to request clarification or add additional context in comments.

1 Comment

@coldcav Please accept the answer if you find it helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.