declared Post request but it showing error "bad request .i want to send the message and restore all the old message but now i am not able to send the Post request:
const sendMessage = async(event) => {
if(event.key === "Enter" && newMessage) {
try {
const config ={
headers:{
"Content-Type": "application/json",
Authorization: `Bearer ${user.token}`,
},
};
setNewMessage("");
const {data} = await axios.post("/api/message", {
content: newMessage,
chatId: selectedChat,
}, config);
console.log(data);
setMessages([...messages, data])
} catch (error) {
toast({
title: "Error Occured!",
description: "Failed to send the Message",
status: "error",
duration: 5000,
isClosable: true,
position: "bottom",
});
}
}
};
the Message controller declared in backend as shown below and it contains the separate chatId and content but the frontend api is not directing to this showing it as error: const sendMessage = asyncHandler(async(req,res) =>{ const { content , chatId} = req.body;
if(!content || !chatId) {
console.log("Invalid data passed into request");
return res.sendStatus(400);
}
var newMessage = {
sender : req.user._id,
content: content,
chatId:chatId,
}
try {
var message = await Message.create(newMessage);
message = await message.populate("sender" ,"firstname pic");
message = await message.populate("chat").execPopulate();
message = await User.populate(message,{
path: "chat.users",
select:"firstname pic email",
});
await Chat.findByIdAndUpdate(req.body.chatId, {
latestMessage:message,
});
res.json(message);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
});
chat Routes in serverjs to route the chat from backend to frontend given as:
app.use("/api/message",messageRoutes);