我正在构建一个类似 whatsapp 的聊天应用程序,并实现该功能 - 当用户点击任何人的名字时,他的聊天内容就会出现,但无法在用户点击时向服务器发送请求
有div,当用户点击它时,它会在Sidebar.js file - 中从服务器(onclick事件处理程序)获取数据
{friends.map((e) => (
<div
onClick={getChatDetails}
key={e.friendName}
className='sidebar_chat_info'>
<Avatar />
<div>
<h2>{e.friendName}</h2>
<p>{getLastMessage()}</p>
</div>
</div>
))}
这是 sidebar.js 文件中的 getChatDetails 函数
const getChatDetails = (e) => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
};
在服务器端,这是index.js file中的路由
服务器运行在 2000 端口
app.post('/message/get', isloggedIn, async (req, res) => {
console.log('REQUESTED!');
try {
const conversation = await req.user.MyConversation.find(
(element) => element.friendName == req.body.friend
);
const messages = await conversationModel.findById(conversation.chats);
res.send(messages);
//await MessageModel.remove({})
} catch (error) {
res.status(500).send(error);
}
});
This is error on browser console , when I am clicking on div
But when I am sending request through postman, I am getting response
当我在其他文件(login.js)中发送请求时,它在那里工作,不知道为什么它只在 Sidebar.js 文件中不起作用
答案 0 :(得分:0)
您遇到的问题是 getChatDetails 中的 e 未定义。原因是 onclick 不传递事件对象。为了将事件对象传递给侧边栏函数,您需要为其附加一个事件侦听器,这比在大多数情况下使用 onclick 好一点(imo)。像这样:
const sidebar = document.getElementsByClassName('sidebar_chat_info')
for (let i = 0; i < sidebar.length; i++) {
sidebar[i].addEventListener('click', handleClick = e => {
//console.log(e.target.textContent);
const Myfriend = e.target.textContent;
axios
.post('http://localhost:2000/message/get', { friend: Myfriend })
.then((response) => {
console.log(response);
})
.catch((error) => console.log(error));
})
答案 1 :(得分:0)
中间件“isLoggedIn”导致问题。问题出在我的身份验证部分,当用户登录后,只有他才能看到主页
我添加了console.log,发现显示“NOT LOGGED IN”
function isloggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
console.log('NOT LOGGED IN !');
res.status(500).send('DENIED PERMISSION!');
}
}
我认为这是因为登录后,我正在从以下位置重定向到主页 Login.js 在第 59 行
history.push('/', { user: response.data });
const submitForm = async (e) => {
e.preventDefault();
axios
.post('http://localhost:2000/login', {
username: username,
password: password,
})
.then((response) => {
history.push('/', { user: response.data });
})
.catch((error) => setIsError(true));
//console.log(user.data); //user.data contains the details
//CALLING THE HOME PAGE AFTER SIGNUP & SENDING DETAILS OF CURRENT USER THERE !
//history.push('/', { user: user.data });
};
也许请求将仅从 Login.js 文件进行身份验证,但我无法从该文件发出其他请求,例如获取聊天详细信息、发送消息等。我将不得不转到主页。这就是为什么我在登录后重定向到主页 在主页上,我的请求未经过身份验证。
在邮递员中,所有路由都在工作,因为我没有切换页面。
登录和注销路由有效,因为它们没有考虑“isLoggedIn”
请建议如何处理需要身份验证的路由,例如发送消息、获取聊天详细信息?
PS - 我的请求甚至没有通过 Login.js 进行身份验证。登录后,这次我没有重定向到主页。登录后我请求路由需要身份验证,它仍然在服务器上显示“未登录”