[英]how to get a user by id with a get request to express using react native?
我正在嘗試使用 express 和 axios 在本機反應中呈現個人資料頁面的一個用戶信息。
這是負責獲取用戶的 controller。
```// GET ONE USER BY ID
module.exports.findOneSingleUser = (req, res) => {
User.findOne({ _id: req.params.id })
.then(oneSingleUser => res.json({ user: oneSingleUser }))
.catch(err => res.json({ message: 'Something went wrong', error: err }));
}```
這是我用來向服務器發出 axios 請求的代碼,我能夠獲取數據庫中的所有用戶,但我希望能夠通過 id 或存儲用於登錄和登錄的令牌呈現一個用戶堅持這是有效的。
```
const ProfileInfo = (props) => {
const { navigation, route } = props
const authCtx = useContext(AuthContext);
const token= authCtx.token
const [userInfo, setUserInfo] = useState([]);
useEffect(() => {
axios.get(`http://localhost:3000/api/users/`)
.then(res => console.log(res.data))
.catch(err => console.log(err))
}, [])```
這是從后端獲取令牌的 util 文件夾中的代碼
import { useNavigation } from '@react-navigation/native';
const BASE_URL = 'http://localhost:3000'
// ! LOGIN FUNCTION
export async function authenticate(email,password ){
const token = await axios.post(BASE_URL + '/api/login',
{
email: email,
password: password,
},{ withCredentials: true }
);
return token;
}
// ! REGISTER NEW USER FUNCTION
export async function createUser(email, password) {
const token = await axios.post(BASE_URL + '/api/register',
{
email: email,
password: password,
},{ withCredentials: true }
);
return token;
}```
this is the screen where I have the profile info componet being used
```import React,{useEffect} from 'react'
import ProfileInfo from '../components/Profile/ProfileInfo';
import Statistics from '../components/Profile/Statistics';
const ProfileScreen = (props) => {
const {navigation} = props
return (
<>
<ProfileInfo navigation={navigation}/>
<Statistics />
</>
)
}
export default ProfileScreen```
How do or What do I need to pass into the url of the axios request to get the data for the user that is logged in? thanks in advance.
when I change the server side to
User.findOne({ token: req.params.token})
&
``` useEffect(() => {
axios.get(`http://localhost:3000/api/users/${token}`)
.then(res => console.log(res.data))
.catch(err => console.log(err))
}, [])```
I get a user but it is only the first user in DB not the user that is logged in... not sure how to get the one user that is logged in.
本文暫無回復,試試以下方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.