我正在开发一个使用带有护照JS的MERN堆栈进行身份验证的应用程序。
应用的ERD如下:
user
site (belongs to user)
page (belongs to site)
我能够注册,登录并获得用户ID和令牌:
* {_id: "5db9760b7ba2c21e9a2659f3", email: “test@gmail.com", token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"}
* email: “test@gmail.com"
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
_id: "5db9760b7ba2c21e9a2659f3"
__proto__: Object
令牌已保存在本地存储中。
现在,我正在尝试通过创建站点来实现ERD的下一步。但是,当我尝试向该网站提出POST
请求时,我得到的用户ID返回未定义:
POST http://localhost:3000/api/users/undefined/sites/ 404 (Not Found)
在终端中,出现此错误:
(node:24299) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "current" at path "_id" for model "Users"
//Create Site
router.post('/:user_id/sites/:site_id/pages', function (req, res, next) {
const saveData = {
userId: req.params.user_id,
siteId: req.params.site_id,
content: req.body.page.content
};
const condition = {
userId: req.params.user_id,
siteId: req.params.site_id
};
console.log(saveData);
Content.exists(condition)
.then((data) => {
if (data == false) {
Content.create(saveData)
.then((data) => {
res.send(data);
});
}
})
})
// LOGIN USER
export const loginUser = async (loginData) => {
const resp = await api.post('/login', { user: loginData });
const token = resp.data.user.token;
storeToken(token);
return (resp)
}
//POST - CREATE SITE
export const newUserSite = async (user_id, data) => {
getToken();
const resp = await api.post(`${user_id}/sites`, { site: data });
return (resp.data);
}
async componentDidMount() {
const user = await loginUser();
this.getUserSites();
const allUserSites = await getUserSites();
this.setState({
users: user,
});
console.log(allUserSites);
};
//Create Site
newSite = async (e) => {
e.preventDefault();
const userID = this.state.users.id;
const site = await newUserSite(userID, this.state.formData);
this.setState(prevState => ({
sites: [...prevState.sites, site],
currentSiteId: site.id,
}))
this.props.history.push("/edit")
}
由于有一个令牌已返回并保存到本地存储中,所以我无法理解为什么用户ID返回未定义状态。