Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expressjs - res.status is not a function TypeError #416

Closed
Chabane opened this issue May 17, 2017 · 25 comments
Closed

expressjs - res.status is not a function TypeError #416

Chabane opened this issue May 17, 2017 · 25 comments

Comments

@Chabane
Copy link

Chabane commented May 17, 2017

Hello,

I used supertest with tape, sinon, proxyquire & expressJS, I got this error :

error: res.status is not a function TypeError: res.status is not a function
    at <path>\index.ts:26:11
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)
(node:21020) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: res.sendStatus is not a function

this is my route function

router.get('/customers', middleware, (req: express.Request, res: express.Response) => {
  let options = {
    uri: url,
    method: 'GET',
  };
  request(req, options).then(body => {
    if (body) {
      res.status(200).send(body);
    }
  }).catch((error) => {
    res.sendStatus(500);
  });
});

my unit test

import * as test from 'tape';
import * as sinon from 'sinon';
import * as request from 'supertest';
import * as proxyquire from 'proxyquire';

const requestStub = sinon.stub();

const stubResponse = {
  statusCode: 200,
  body: { body: 'body' }
};

const api = proxyquire('./', { 'api-request': requestStub });
requestStub.returns(Promise.resolve(stubResponse));

test('Get /customers', (assert) => {

  const agent = request.agent(api);

  agent
    .get('/customers')
    .expect(200)
    .set('Accept', 'application/json')
    .end((err, res) => {
      var expectedThings =
        {
          "some" : "data"
        };
      var actualThings = res.body;

      assert.error(err, 'No error');
      assert.same(actualThings, expectedThings, 'Retrieve list of things');
      assert.end();
    });
});

Do you have any idea?

@nikhedonia
Copy link

nikhedonia commented Jan 11, 2018

I encountered the same error when applying supertest on a express route.

const routes = express.Router();
routes.get('/', ()=> res.status(200).send('blub'))
request(routes).get('/').end() // status not a function
request(app.use(routes)).get('/').end() // works

@ianaz
Copy link

ianaz commented May 29, 2018

Same issue. The solution of @nikhedonia brings it to work

@rimiti rimiti closed this as completed Sep 19, 2018
@boompig
Copy link

boompig commented May 14, 2019

Hi @rimiti , would you mind giving a working example that adapts @nikhedonia 's PoC above?

Additionally, can you explain why arrow functions are not supported in this context? Since arrow function are now (at time of writing) the default way to declare functions in node (the function keyword is being phased out of most example code and books), can you please explain the design considerations of not having supertest work with arrow functions in this particular example?

I understand you're quite busy and appreciate the help 😄

@TakanashiOuken
Copy link

Having the same issue even with function() {}

@iLyxa3D
Copy link

iLyxa3D commented Jul 24, 2019

Fixed, in my case..
Just add "next" to the variables list (err, req, res, next)

app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({error: 'an error occurred'});
});

From documentation: https://expressjs.com/ru/api.html

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.

@NBNARADHYA
Copy link

NBNARADHYA commented Sep 10, 2019

Having the same issue @rimiti . Could u please reopen the issue or look into #596 ?

@pedritusz
Copy link

he tendido el mismo problema y lo que pasa es que tienes definida la request del get con req y el de la funcion request tambien esto deveria funcionar:
router.get('/customers', middleware, (req: express.Request, res: express.Response) => {
let options = {
uri: url,
method: 'GET',
};
request(otherRequest, options).then(body => { // change a definition of request
if (body) {
res.status(200).send(body);
}
}).catch((error) => {
res.sendStatus(500);
});
});

@ats1999
Copy link

ats1999 commented Jun 1, 2020

I also have the same problem.

router.post('/signin',(req,res,next)=>{
    const username=req.body.username;
    const password=req.body.password;
    
    // check vaild input
    if(!username||!password){
        return res.status(422).json({err:"Please add all the fields."})
    }

    User.findOne({userId:username})
    .then(saveduser=>{
        console.log(saveduser)
        if(saveduser){
            const hash=saveduser.password;
            bcrypt.compare(password,hash,(err,res)=>{
                if(err)
                    console.log(err);

                if(res)
                    return res.status(422).json({error:"This line is causing error!"})
                else res.json({err:"Email/password do not match!"})
            })
        }
    .catch(err=>{
        console.log(err);
    })
})

Error

TypeError: res.status is not a function

Can, somebody explain me why i am getting this error.

@mathurin59000
Copy link

@ats1999 You are using res variable two times. One is the response object and the second is the bcrypt result. Rename the second res (in bcrypt callback) so as to not overwrite your response object.

@divyanshu59
Copy link

@mathurin59000 Thankyou, I was doing same mistake

@Mnabawy
Copy link

Mnabawy commented Oct 31, 2020

@iLyxa3D Thanks

@IbrahimShamma99
Copy link

I faced the issue in production
the response request was
res.status(401)
I just added unauthorized
res.status(401).send({auth:false})

pejuam added a commit to kavi-fi/meku that referenced this issue Nov 26, 2020
@RidhikGovind
Copy link

Fixed, in my case..
Just add "next" to the variables list (err, req, res, next)

app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({error: 'an error occurred'});
});

From documentation: https://expressjs.com/ru/api.html

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.

Thank you so much ! The solution as well as your explanation helped!

@narendraktw
Copy link

Always use (err, req, res, next) in sequence else you would also get this res.status error.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({error: 'an error occurred'});
});

@SohaibArbiBakcha
Copy link

SohaibArbiBakcha commented Jul 18, 2021

code with the error of res.status is not a function TypeError


app.use(function (err, res, req, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).json({ error: "Unauthorized" });
  }
});

clean code work well

app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).json({error : "Unauthorized"});
  }
});


i don't know where is the error lol

@VimanshuAryan
Copy link

image

I'm getting the same error and adding next to the variables didn't work

@Tejv1708
Copy link

export const getPosts =async(res , req , next) => {
try {
const postMessage = await PostMessage.find();

console.log(PostMessage);

res.status(200).json(postMessage);
} catch (error) {
res.status(404).json({message : error.message })
}
}
;

I got the error : res.status() is not a function .

@mathurin59000
Copy link

Request is the first parameter, Response the second and Next the third. Invert req and res in your parameters.

@Tejv1708
Copy link

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import { configureStore } from '@reduxjs/toolkit'
import { applyMiddleware , compose} from 'redux';
import thunk from 'redux-thunk' ;
import reducers from './reducers';
import App from './App';

const store = configureStore(reducers, compose(applyMiddleware(thunk))) ;

ReactDOM.render(


,
document.getElementById('root')
);

Error is : "reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers

@mathurin59000
Copy link

Instead of passing directly reducers, pass an object like this, {reducer: reducers} (reducers which is your combineReducers)

@Tejv1708
Copy link

Thanku @mathurin59000

@Tejv1708
Copy link

ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17

//Why did this error come even after my website run ..?

@Tejv1708
Copy link

Do classes consume any memory in java ..? if yes tell me a reason.

@Tejv1708
Copy link

@mathurin59000 Do classes consume any memory in java? if yes tell me a reason.

@AniketKumar06
Copy link

import adminModels from "../../models/admin/adminModels.js";

export const adminRegister = async ( request , response, next)=> {
    const { name, email, phone, password } = request.body;
    try {
        if (!name) {
            return response.status(500).json({
                sucess: false,
                msg: "Name is Required"
            });
        }
        if (!email) {
            return response.status(500).json({
                sucess: false,
                msg: "Email is Required"
            });
        }
        if (!phone) {
            return response.status(500).json({
                sucess: false,
                msg: "Phone is Required"
            });
        }
        if (!password) {
            return response.status(500).json({
                sucess: false,
                msg: "Password is Required"
            });
        }

        // check wheather user exist or not
        const exit = await adminModels.findOne({
            email: email
        });

        if (exit) {
            return response.status(202).json({
                success: "User already Exit",
                msg: exit
            });
        }


        let newAdmin = await adminModels.create(req.body);
        res.json({
            success: true,
            message: 'Admin Register successfully',
            student: newAdmin
        });
    }

    catch (err) {
        console.log(err);
    }
}

TypeError: response.status is not a function

I got this error please help me to solve this issus

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests