HIMANSHU KUMAR AMB
HIMANSHU KUMAR AMB

Reputation: 35

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);
}

Upvotes: 0

Views: 1038

Answers (2)

Abbas
Abbas

Reputation: 1255

When you do

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

It writes the response headers. You again call res.json() which also writes response headers, but the headers have already been sent previously.

You need to make sure you call res.json once.

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) // status 200 is default here
    } catch (error) {
        res.json({ message: error.message }).status(400)
    }

}

Upvotes: 2

Ladi Adenusi
Ladi Adenusi

Reputation: 1082

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 })
    }

}

Upvotes: 0

Related Questions