1

I'm attempting to use a variable userEmail (which is assigned the user's email who is currently logged into my app) as a query for my api as I only want to search and return documents from my mongodb that relate to that specific email. I'm struggling to figure out how to pass this variable from my reactjs app to my api and utilising it, I don't even know if it is possible so any help would be great.

I'm using axios to make my GET request.

api.js contains my api helper functions

export async function surveyApiGet () {

    let response = await axios.get('http://localhost:6000/'); // dateApi.js

    return response.data;
}

dateApi.js is the api surveyApiGet() calls and at the moment my query is just regex that matches any emails, rahter than filtering to just the current user.

let MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
const express = require('express');
const app = express();

app.use(express.json());

app.get('/', function (req, res) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("manderleydb");
        var query = { userId : /^(.)/ };
        dbo.collection("manderleySurveyCompleted").find(query).sort({ date: 1}).limit(1)
            .toArray(function(err, result) {
                if (err) throw err;
                console.log(result);
                db.close();
                res.status(200).json(JSON.stringify(result));
        });
    });
});

app.listen(6000, () => {
    console.log('listening on port 6000');
});

Landing.js is where I make the call to my api helper function

surveyApiGet()
        .then(response => {
          // code
        })
        .catch(err => {
          err.message;
        });

1 Answer 1

1

For this, you can do a POST request to your Nodejs API and you can include the user's email with that request. To do so what you have to do is something like the following.

const usersEmail = "[email protected]"

Then through Axios, you can post this code to Nodejs API as follows.

const data = await axios.post("http://localhost:6000/", {
    usersEmail : usersEmail
});

After you send this to Nodejs you can hold the value of the user's email through the request's body as follows. Change your endpoint to post instead of get.

app.post("/", function (req, res) {
     const userEmail = req.body.userEmail;

     //Put your MongoDB query and the status code here.

})

Drop a comment if you have any unclear points.

Sign up to request clarification or add additional context in comments.

Comments

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.