Search code examples
node.jsreactjsmongodbexpressmern

How do I debug server-side errors on MERN?


I have this front-end code:

export const CreatePage = () => {
const auth = useContext(AuthContext)
const {request} = useHttp()
const [content, setContent] = useState('')
const [title, setTitle] = useState('')
const [lead, setLead] = useState('')

useEffect(() => {
    window.M.updateTextFields()
},[])

const postHandler = async () => {
    try {
        const data = await request('/api/post/generate', 'POST', {title: title, lead: lead, content: content}, {
            Authorization: `Bearer ${auth.token}`
        })
        console.log(data)
    } catch (e) {}
}

And this back-end code:

router.post('/generate', auth, async (req, res) => {
try {
    const baseURL = config.get('baseURL')
    const {title, lead, content} = req.body

    // if (!title || !lead || !content) {
    //     return res.status(422).json({error: 'Please, input ALL fields'})
    // }

    const Post = new Post({
        title, lead, content, owner: req.body.user.userId // req.user.userId
    })

    await Post.save()
    res.status(201).json({Post})

} catch (e) {
    res.status(500).json({message: 'Something went wrong'})
}})

I've tried a lot of things, but I still get this error. I know this is a server-side error, but that's all I have been able to figure out.

P.S. If there are any questions about the code, I will add it later.

UPD: By the way, could it be a problem's reason? Console log:

[1] Proxy error: Could not proxy request /api/post/generate from localhost:3000 to http://localhost:5000.

Solution

  • Probably, it's because of cors, you just can't send request from different url's. Try to install cors and configure it:

    const cors = require("cors");
    
    app.use("/", require('./src/routes'));
    app.use(cors({
      origin: '*'
    }))