Reputation: 129
I make an axios request from the frontend through node to a Mongodb database requesting a userName based on userId. The request comes back as having been made, but no data is returned.
This is the Mongodb users collection:
{
"_id" : ObjectId("5e1b46cb2e6f4c98904598b0"),
"userId" : "[email protected]",
"userName" : "Fool",
}
This is the 'Users' schema file
users model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userId: String,
userName: String,
});
module.exports = mongoose.model('Users', UserSchema);
This is the backend request:
backend:
const express = require('express');
const UserRoute = express.Router();
const Users = require('../Models/UserModel');
UserRoute.route('/fetchUserName').get(function (req, res) {
Users.find({userId: req.query.userId}, {userName: 1})
.exec(function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
console.log(user.data);
res.json(user.data);
}
});
});
Here is the actual request from the frontend:
getUserName = () =>
axios.get('http://localhost:4000/Users/fetchUserName', {params: {userId: '[email protected]'}})
.then(res => {
return res.data;
});
};
res.data is returned as an empty string.
Any ideas why the request does not work.
Upvotes: 1
Views: 6968
Reputation: 21
The userId should probably send as a string. So either:
const params {
userId: '[email protected]'
}
axios.get('http://localhost:4000/Users/fetchUserName', { params })
or
axios.get('http://localhost:4000/Users/fetchUserName', {params: {userId: '[email protected]'}})
Upvotes: 1