Search code examples
node.jsreactjsmongodbaxiosmern

Cannot set headers after they are sent to the client (error when i'm striking axios post requrest)


**I'm sending response to my Axios call but I'm keep getting the above error **

import User from "../model/UserSchema.js"
export const getuser = async (req, res) => {
    res.status(200).json("hello from code with himanhsu 12315464968 darling")
    try {
        let user = await User.find()
        res.json(user)
    } catch (error) {
        res.json({ message: error.message })
    }

}

error .. : **Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (C:\Users\HIMANSHU\Documents\REACT\16_MERN_operations\server\node_modules\express\lib\response.js:771:10) at ServerResponse.json (C:\Users\HIMANSHU\Documents\REACT\16_MERN_operations\server\node_modules\express\lib\response.js:264:10) at getuser (file:///C:/Users/HIMANSHU/Documents/REACT/16_MERN_operations/server/controller/UserContoller.js:9:13) at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use node --trace-warnings ... to show where the warning was created)
(node:3732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,

*my API call from axios *

import axios from "axios"
const url = "http://localhost:8000/users"
export const getUsers = async () => {
return await axios.get(url);
}

Solution

  • You should get rid of this line in your express function

    res.status(200).json("hello from code with himanhsu 12315464968 darling")
    

    You will then have this

    import User from "../model/UserSchema.js"
    export const getuser = async (req, res) => {
        try {
            let user = await User.find()
            res.json(user)
        } catch (error) {
            res.json({ message: error.message })
        }
    
    }