我正在使用reactJs,postgres,express和prisma构建一个全栈真实的地产应用程序。
当我想检查我的本地存储中是否存储了令牌时,它会失败并返回一条错误消息,给出404未找到。
我试着寻找解释,但它总是同样的故事,它不适用于我的情况。
最终,我希望能够从登录的用户获取数据,并在我的前端使用它。如果任何人有任何额外的提示如何做到这一点,请让我知道!
== API ==
- 索引.js*
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const express = require('express');
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000
app.use(cors());
app.use(express.urlencoded({ extended: true }))
app.get('/', (req, res) => {
res.send('Testing')
})
app.use('/auth', authRoutes);
app.use('/user', userRoutes);
app.listen(PORT, () => {
console.log("app is running!")
});
- user.js(routes)*
const { PrismaClient } = require('@prisma/client')
const express = require("express");
const router = express.Router();
const prisma = new PrismaClient();
router.get('/user/me', async (req, res) => {
try {
const user = await prisma.user.findUnique({
where: { id: req.user.id },
});
console.log(user);
res.status(200).json({ user });
} catch (error) {
res.status(500).json(error);
}
});
module.exports = router;
== APP ==
- Authcontext.js*
import { createContext, useReducer } from "react";
import { useEffect } from "react";
import axios from "../config/axios";
const AuthContext = createContext()
const authReducer = (state, action) => {
switch(action.type) {
case 'LOGIN':
return { user: action.payload }
case 'LOGOUT':
return { user: null }
default:
return state
}
}
const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, {
user: null
})
useEffect(() => {
const user = localStorage.getItem('token')
if (user) {
dispatch({ type: 'LOGIN', payload: user })
}
}, [])
const getUserInfo = async () => {
const token = localStorage.getItem('token');
if (token) {
try {
const res = await axios.get(`/user/me`, {
headers: {
'x-auth-token': token,
},
});
console.log(res.data.user);
dispatch({
type: 'LOGIN',
payload: {
user: res.data.user,
},
});
} catch (err) {
console.error(err);
}
} else {
delete axios.defaults.headers.common['x-auth-token'];
}
};
useEffect(() => {
const verifyUser = async () => {
if (!state.user) {
await getUserInfo();
}
};
verifyUser();
}, []);
const register = async (registerData) => {
try {
const response = await axios.post("/register", registerData);
return response.data;
} catch (error) {
if (!error.response) {
return { status: "ERRROR", message: "No Server Response" };
} else if (error.response.status === 409) {
return error.response.data;
} else if (error.response.status === 400) {
return error.response.data;
} else {
return error.response.data;
}
}
};
const login = async (loginData) => {
try {
const response = await axios.post("/login", loginData);
localStorage.setItem("token", response.data.token);
await getUserInfo();
return response.data;
} catch (error) {
if (!error.response) {
return { type: "ERROR", message: "No Server Response" };
} else if (error.response.status === 400) {
return error.response.data;
} else if (error.response.status === 401) {
return error.response.data;
} else {
return error.response.data;
}
}
};
const logout = async () => {
try {
localStorage.removeItem("token");
dispatch({
type: "LOGOUT",
});
} catch (error) {
console.log(error.response);
}
};
return (
<AuthContext.Provider value={{ ...state, dispatch, register, login, logout }}>
{ children }
</AuthContext.Provider>
)
}
export {AuthContext, authReducer, AuthContextProvider}
1条答案
按热度按时间jqjz2hbq1#
请不要在
authRoutes
和userRoutes
中重新声明根路由名称。对于当前形状,您必须将其称为:相反,要保持axios调用现在的声明,请如下声明路由:
然后你就能正确地调用它
您可以在express.js文档中阅读更多内容。