【问题标题】:TypeError: res.status is not a functionTypeError:res.status 不是函数
【发布时间】:2020-04-22 08:33:29
【问题描述】:

我正在制作一个功能,允许我在我的 express api (nodejs) 中将图片上传到 imgur, 我在调用返回承诺的函数时遇到错误:

TypeError: res.status 不是函数 在uploadpicture.then

这是我的代码: 出现错误的地方:

  router.post('/upload', (req, res, next)=> { 
    var busboy = new Busboy({headers: req.headers});
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        if(fieldname == 'image') {
            // the buffer
            file.fileRead = [];
            file.on('data', function(data) {
                // add to the buffer as data comes in
                this.fileRead.push(data);
            });

            file.on('end', function() {
                // create a new stream with our buffered data
                var finalBuffer = Buffer.concat(this.fileRead);
                upload = uploadpicture(finalBuffer).then((res)=>{ //success request
                  console.log(res);
                  res.status(200).json({success: true, message: "Successfully uploaded !", url: res.data.link});
                },(err)=>{ //error
                  res.status(500).json({success: false, message: "Error happenned while uploading !"});
                }).catch((error)=>{
                  console.log(error);
                  res.status(500).json({success: false, message: "Error happenned while uploading !"});
                });

            })
        }
    });
    busboy.on('finish', function() {
        //busboy finished
    });
    req.pipe(busboy);
});

还有功能:

function uploadpicture(stream){ //get picture stream
    return new Promise((resolve, reject)=>{
    var options = {
      uri: 'https://api.imgur.com/3/image',
      method: 'POST',
      headers: {
          //'Authorization': 'Client-ID ' + config.client_id_imgur // put client id here
      },
      formData: {
          image: stream,
          type: 'file'
      },
      auth: {
        bearer: config.access_token_imgur,
      }
  };

  request(options)
      .then((parsedBody)=> {
          resolve(parsedBody);
      })
      .catch((err)=> {
        console.log(err);
        reject(err.toString())
      });
    });
  }

代码完美运行,但我不知道为什么突然发生这个错误, 我试图:

将箭头函数更改为 function(){} 在路由参数旁边添加

没有成功,感谢您的帮助

【问题讨论】:

    标签: javascript node.js api express promise


    【解决方案1】:

    接受的答案直接解决了 OP 的问题,但我发布了另一个解决方案,因为您也可能在其他地方遇到此错误。

    当你有:

    api.use((error: ErrorRequestHandler, request: ExpressRequest, response: ExpressResponse) => {
      response.status(500).end() // response.status is not a function
    })
    

    因为错误处理路径必须接受 express 的 4 个参数以将其识别为错误中间件。

    api.use((error: ErrorRequestHandler, request: ExpressRequest, response: ExpressResponse, next: NextFunction) => {
      response.status(500).end()
    })
    

    只需添加下一个函数(或您缺少的任何参数)即可修复它。

    https://github.com/visionmedia/supertest/issues/416#issuecomment-514508137

    【讨论】:

    • 很好记,虽然问题与中间件无关,但可能有类似问题
    • 如果您的代码来自app.use 接受3 个参数而不是4 个参数的时间,就会出现此错误?
    • closeapp.use 的文档,向下滚动到error-handling..
    【解决方案2】:

    此时:

    upload = uploadpicture(finalBuffer).then((res)=>{ //success request
    

    res 是 promise uploadpicture 函数的结果(即parsedBody),而不是快速路由中的res。所以确实,它没有status 功能。尝试更改 then 回调名称,如:

    upload = uploadpicture(finalBuffer).then((otherName)=>{ //success request
    

    【讨论】:

    • res 是保留字吗?我不明白你的意思。如果我使用othername 它有一个status 函数?
    • 其实不是保留字。重点是res 是快速路由的响应变量的名称。当他将promise.then 响应命名为res 时,.then 范围假定res 来自已解决的承诺,而不是来自快速路由。实际上它没有.status 功能。重命名 promise.then res 解决了这个问题,因为我们通常从 express 路由中调用 res 对象。如果您希望将快速路由对象重命名为例如otherNameElse,那么您需要调用otherNameElse.status 函数来响应路由。
    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 2017-05-06
    • 2019-12-20
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多