Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
POST http://localhost:3000/api/message 400 (Bad Request) xhr.js:210

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);
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda