Home > Enterprise >  Why am I getting a "400: Bad Request" but the request successfully posts to my DB
Why am I getting a "400: Bad Request" but the request successfully posts to my DB

Time:11-08

I am not sure what is happening. I had all the same code setup in dev using localhost and everything was working fine. I hosted my app to Vercel and my API to heroku and from what I can tell the API is working perfectly. The issue now is when I make a post request I get a 400 Bad Request error in the browser but it still makes the request and posts to my DB I have setup. Any help can be appreciated. I built this application in a MERN stack with NEXT.js

Here is my client side Post request

const postSubmit = async e => {
        e.preventDefault();

        try {
            const { data } = await axios.post('/create-post', { content, image });
            
            if(data.error) {
                toast.error(data.error);
            } else {
                setPage(1);
                newsFeed();
                toast.success("Post created");
                setContent('');
                setImage({});
                // socket.emit('new-post', data);
            }
        } catch(e) {
            console.log(e);
        }
    }

Here is my server side handling of the post request

export const createPost = async (req, res) => {
    const { content, image } = req.body;
    if(!content.length) {
        return res.json({
            error: 'Content is required'
        })
    }

    try {
        const post = new Post({ content, image, postedBy: req.user._id });
        await post.save();

        const postWithUser = await Post.findById(post._id).populate('postedBy', '-password -secret');

        res.json(postWithUser);
    } catch (e) {
        console.log(e);
        res.sendStatus(400);
    }
};

And here is what the browser is telling me

Chrome Browser Info

CodePudding user response:

This is most likely caused by a typo on the MongoDB connection string (URI), similar to this answer.

In the linked answer, the typo was the semi-colon in &w=majority;. In your case, the value is somehow majorityDATABASE=, so double-check your MongoDB connection string and try to remove the extra DATABASE= in the write concern parameter.

CodePudding user response:

It's likely that the await Post.findById() call is not finding a result which could be throwing an error when you try to call res.json(postWihUser). That would then cause an error when postWithUser is not defined.

What is logged to the server's terminal when an error occurs? That should help you identify the problem.

  • Related