【问题标题】:Node.js - "TypeError - res.setHeader is not a function"Node.js - “TypeError - res.setHeader 不是函数”
【发布时间】:2022-01-23 09:20:11
【问题描述】:

我正在尝试将 JSON 从 URL 加载到变量并将其发送回客户端的 javascript

var getJSON =require('get-json');

app.post('/json', function(req, res) {
    getJSON(url, function(err, res){
        if(err)
        {
           console.log(err);
        }
        else
        {
           res.setHeader('content-type', 'application/json');
           res.send(JSON.stringify({json: res.result}));
        }
    });
});

每次我运行代码时,服务器都会说 res.setHeader 不是一个函数,其余的都会中断。

【问题讨论】:

  • 您有多个同名变量 -- res。由于名称相同,不可能同时引用两者(res.setHeader()res.result)。不过,重命名其中一个,即使是轻微的,也应该使它们都可以访问。参考:Variable Shadowing

标签: javascript node.js express getjson


【解决方案1】:

postgetJSON 回调具有相同的 res 变量名称。 试试这个:

var getJSON =require('get-json');

app.post('/json', function(req, res) {
  getJSON(url, function(err, response){
    if(err)
    {
       console.log(err);
    }
    else
    {
       res.setHeader('content-type', 'application/json');
       res.send(JSON.stringify({json: response.result}));
    }
  });
});

【讨论】:

    【解决方案2】:

    对我来说,这是在我建立的论坛中获取数据时发生的。我在这篇博文中找到了解决方法: https://dev.to/shailesh6363/facing-error-res-setheader-not-a-function-2oc9

    我根据 atul singh 在 cmets 中添加了代码。

    app.js 的变化

    app.use((res, next) => {
      ....
    });
    

    app.use((req, res, next) => {
      ....
    });
    

    现在应用程序没有崩溃,它成功获取并显示数据

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 1970-01-01
      • 2020-10-25
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2018-06-14
      相关资源
      最近更新 更多