【问题标题】:Cannot set headers after they are sent to the client (error when i'm striking axios post requrest)将标头发送到客户端后无法设置标头(当我点击 axios post requrest 时出错)
【发布时间】:2021-10-25 00:59:24
【问题描述】:

**我正在发送对我的 Axios 调用的响应,但我不断收到上述错误 **

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

}

错误..: **发送到客户端后无法设置标头 在 ServerResponse.setHeader (_http_outgoing.js:558:11) 在 ServerResponse.header (C:\Users\HIMANSHU\Documents\REACT\16_MERN_operations\server\node_modules\express\lib\response.js:771:10) 在 ServerResponse.json (C:\Users\HIMANSHU\Documents\REACT\16_MERN_operations\server\node_modules\express\lib\response.js:264:10) 在 getuser (file:///C:/Users/HIMANSHU/Documents/REACT/16_MERN_operations/server/controller/UserContoller.js:9:13) 在 processTicksAndRejections (internal/process/task_queues.js:93:5)
(使用node --trace-warnings ... 显示警告的创建位置)
(节点:3732)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。在未处理的 Promise 拒绝时终止节点进程,

*我从 axios 调用的 API *

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

【问题讨论】:

    标签: node.js reactjs mongodb axios mern


    【解决方案1】:

    当你这样做时

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

    它写入响应headers。您再次调用res.json(),它也会写入响应标头,但headers 之前已经发送过。

    您需要确保您致电res.json 一次。

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

    【讨论】:

      【解决方案2】:

      你应该在你的 express 函数中去掉这行

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

      你会得到这个

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-18
        • 2020-05-30
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2021-04-07
        • 1970-01-01
        相关资源
        最近更新 更多