【问题标题】:Getting error - Can't set 'headers' of undefined出现错误 - 无法设置未定义的“标题”
【发布时间】:2025-12-29 18:30:06
【问题描述】:

我被这个错误困住了 - Can't set Headers of Undefined

代码参考


单独定义标题:

var headers = function (req,res,next){
    res.setHeader("Access-Control-Allow-Origin", "[*]");
    res.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");

    console.log("Inside headers")
}

定义了我想运行的第一个函数:

var middleware1 = function (req, res, next) {
    headers();

    console.log("Before Get method middleware")
    console.log("middleware1");

    collection.find({}, {
        name: 'Task 1'
    }).toArray((error, result) => {
        if (error) {
            console.log("It is the find -> /tasks method error");

            return res.status(500).send(error);
        }

        next();
    })
}

定义第二个函数:

var middleware2 = function (req, res, next) {
    headers();
    console.log("middleware2");
    
    collection.find({}, {name: 'Task 4'}).toArray((error, result) => {
        if (error) {
            console.log("It is the find -> /tasks method error");

            return res.status(500).send(error);
        }
    })
    next();
}
      

定义了 validateParams:

Defined the Final value to be run: 

const fn1 = (req, res, next) => {
middleware1();

console.log("1");
next();
};

 const fn2 = (req, res, next) =>{
middleware2();

console.log("2");
next();
};

 const fn3 = (req, res, result) => {
 collection.find({}).toArray((error, result) => {
    if (error) {
        console.log("It is the find -> /tasks method error");
        return res.status(500).send(error);
    }

    res.send(result);
    console.log("result");
  });
  };
**Final Call**

  app.get("/2498", function fn1(req, res, next) {  
  headers(req, res, next);

    

        //In Going the right way --> Task 1 to Task 4     

              middleware1(req, res, next);

              console.log("1");
              // next();
              },
              function fn2 (req,res,next) {
              
                headers(req, res, next);

                middleware2(req, res, next);

                console.log("2");
                // next();
              } ,function fn3  (req,res,next) {

              headers(req, res, next);

              collection.update(
                
                  { 'taskId': 1,   'parent': 'yes!' ,  'projectId' : 1,   
   'content': { 'name': 'Task 1', 'predecessors':[], 'successor': [2] } },
                  { 'taskId': 4,   'parent': 'na' ,    'projectId' : 2, 
  'content': { 'name': 'Task 6' , 'predecessors':[], 'successor': [3] } }
                  ).toArray((error, result) => {

                if(error) {
                    console.log("It is the find -> /tasks method error");
            
                    return res.status(500).send(error);   
                }
                console.log("Inside getToBeAssumed  --> Task 4  
           .....validateParams.....");
            
               console.log("The end = ", result);

                             
              })
              })
              ```

详细错误:

TypeError:无法读取未定义的属性“setHeader” 在标题处 (D:\mongodb_test_app\app-module-1.js:231:7) 在 fn1 (D:\mongodb_test_app\app-module-1.js:303:7) 在 Layer.handle [as handle_request] (D:\mongodb_test_app\node_modules\express\lib\router\layer.js:95:5) 在下一个(D:\mongodb_test_app\node_modules\express\lib\router\route.js:137:13) 在 Route.dispatch (D:\mongodb_test_app\node_modules\express\lib\router\route.js:112:3) 在 Layer.handle [as handle_request] (D:\mongodb_test_app\node_modules\express\lib\router\layer.js:95:5) 在 D:\mongodb_test_app\node_modules\express\lib\router\index.js:281:22 在 Function.process_params (D:\mongodb_test_app\node_modules\express\lib\router\index.js:335:12) 在下一个(D:\mongodb_test_app\node_modules\express\lib\router\index.js:275:10) 在 SendStream.error (D:\mongodb_test_app\node_modules\serve-static\index.js:121:7) 在 SendStream.emit (events.js:315:20) 在 SendStream.error (D:\mongodb_test_app\node_modules\send\index.js:270:17) 在 SendStream.onStatError (D:\mongodb_test_app\node_modules\send\index.js:421:12) 在下一个(D:\mongodb_test_app\node_modules\send\index.js:735:16) 在 onstat (D:\mongodb_test_app\node_modules\send\index.js:724:14) 在 FSReqCallback.oncomplete (fs.js:183:21)

【问题讨论】:

  • 当你调用一个函数时,你实际上需要传递参数,否则所有参数都将是未定义的。

标签: javascript node.js mongodb express


【解决方案1】:

你来电:

headers();

middleware1();

middleware2();

但是,所有这些函数都需要几个参数。您需要传递这些参数:

headers(req, res, next);
middleware1(req, res, next);
middleware2(req, res, next);

从技术上讲,headers 函数实际使用的唯一参数是 res,因此您可以将其定义更改为只有一个参数 res 并只传递那个参数。

【讨论】:

  • 嗨@jfriend00 .... 我做了以下更新。但它也没有成功。你能建议一些其他的方法吗?
  • @SuchetaShrivastava - 好吧,您还调用了middleware1();middleware2(),所以也不要将参数传递给它们。说真的,如果调用者没有传递参数,你就不能使用参数——在你的所有代码中。我们已经向您指出了这一点。我们不应该在你的代码中找到所有的实例——你应该可以自己做。此外,当您遇到此类错误时,使用console.log() 或在调试器中检查您的参数是什么是基本调试。你应该早在来这里之前就自己做这件事。这是基本调试。
  • @SuchetaShrivastava - 请注意,当您修复此问题时,您会产生其他问题,因为您尝试在middleware1fn1 中多次调用next()。不能那样做。这段代码有很多错误。您正在尝试通过调用 next() 来处理指示完成的异步函数,就像它们是同步的一样,这是行不通的。
  • 嗨 @jfriend00 .... 当我在 --> app.get('/2498',....) 中评论 next() 时 ----> 我收到了这个错误 -- >TypeError:executeLegacyOperation 的最后一个参数必须是回调
  • 你能帮我解决一下如何在我的代码中的所有错误中加上“结尾”,以使其顺利运行
最近更新 更多