Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: res.status is not a function

I'm making a function that permits me to upload a picture to imgur in my express api (nodejs), i'm encoutering an error when calling a function returning a promise:

TypeError: res.status is not a function at uploadpicture.then

This is my code: Where error is raised:

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

And the function :

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

The code works perfectly, but i don't know why suddendly this error happened, i tried to :

change arrow functions to function(){} Add next to the route parameters

Nothing worked, Thanks for your help

like image 804
nonoom Avatar asked Jan 03 '20 19:01

nonoom


People also ask

Why res json is not a function?

Conclusion # The "response. json is not a function" error occurs when we call the json() method on an object that is not the Response object that resolves from the promise the fetch() method returns, or call the json() method on the return value from calling an axios method.

What is RES status?

The res. status() function set the HTTP status for the response. It is a chainable alias of Node's response.

Can't set headers after they are sent?

The "Cannot set headers after they are sent to the client" error occurs when the server in an express. js application sends more than one response for a single request, e.g. calling res. json() twice. To solve the error, make sure to only send a single response for each request.


2 Answers

The accepted answer directly addresses the OP's problem, but I post another solution since you can also encounter this error in other places.

When you have:

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

Because the error handling route must accept 4 arguments for express to identify it as an error middleware.

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

Just adding the next function (or whatever argument you're missing) will fix it.

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

like image 59
Matriarx Avatar answered Oct 11 '22 10:10

Matriarx


At this point:

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

the resis the result of promise uploadpicture function (that is the parsedBody), not the res from the express route. So indeed, it has no status function. Try change the then callback name like:

upload = uploadpicture(finalBuffer).then((otherName)=>{ //success request
like image 22
Luiz Fernando da Silva Avatar answered Oct 11 '22 09:10

Luiz Fernando da Silva