简体   繁体   中英

Res value is null in an app.get call done from vue.js front-end to express back-end

I am calling this code from the front-end and confirmed that there is a proper db connection and that the Id value is properly passed, and that there is a corresponding value in the database, but for some reason, res is null. What am I missing?

app.get("/api/walletlogin/user/:userId", (req, res) => {

 id = req.params.userId
 var query = {_id: id}
  db.collection("Users").findOne(query, (err, result) => {
  if (result) {
    console.log(result.userName)
  } else {
    console.log('No User')
  }
})

Here is the front-end call:

  axios.get('/api/walletlogin/user/' + accounts)
      .then((response) => {
        console.log('Logged in With ' + accounts)
        router.push('/account')
      })
      .catch((errors) => {
        console.log('Cannot log in')
      })
  }).catch((err) => {
    console.log(err, 'err!!')
  })

to search by id, you must use the ObjectID class from the mongodb package. Here is an example invented by me, it does not reflect the real work, but I hope it will become clear on it:

const { ObjectID } = require('mongodb');

const id = '5ee4f69bfa0b960de8aec158'; // in your example is req.params.userId
db.collection('users').findOne({ _id: new ObjectID(id)}, (error, result) => {
    if (error) {
        throw error;
    }
    console.log(result);
})

You could try to convert your id to an objectID.

var ObjectId = require('mongodb').ObjectId; 
var id = ObjectId(req.params.userId);

I am adding the details of the issue initially encountered in case someone else would experience it in the future. The value that is passed from the front-end is a cryptocurrency address. For some reason, some of the characters passed were upper-case, while the same address had been stored in the database with these same characters as lower case. Thus, one needs to add code to make sure that the case of the letters found in the respective addresses is ignored.

J

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM