node.jsexpresspostmodulerequest

Node Express is not sending a custom error message


I'm trying to make an npm module in which the user needs to send his token and id to be able to connect.

This is the module code:

var https = require('https');
var fetch = require('node-fetch')


module.exports = class Cloud_client {
   constructor(client,token){
      this.token = token ;
      this.client = client;
      if(!token) return console.error(`[cdl.js] No token provided`);
      if(!client)  return console.error(`[cdl.js] No Client Id provided`);
   }
  login() {
     fetch(`https://www.cloudlist.xyz/isvalid/${this.token}`, {
        method: "POST",
        headers: {
        "Content-Type": "application/json"
        },
        body:JSON.stringify({client:this.client}),
          }).then(async response => {
            console.log(response)
    return console.error(`[cdl.js] ${response.statusText}`); // eslint-disable-line no-console

    })
  }
}

Server Side Post Handler:

    app.post("/isvalid/:token", limiter ,async (req, res) => { 
  if(!req.body.client) return res.status(204).send({message: 'No id provided'});
  if(!req.params.token ) return res.status(204).send({message: 'No token provided'});
database.ref(`Bots/${req.body.client}`).once("value",function(data) {
  if(data.val() === null) return res.status(204).send({message: 'Invalid user'});
  if(!data.val().apiKey) return res.status(204).send({message: "This Client doesn't have an api key yet"});
  if(data.val().apiKey === req.params.token) {
    res.status(200 ).send({message: `Logged in as ${data.val().bot_name}`});
  }else {
    return res.status(401).send({message:"Incorrect authorization token."});   
  } 
})
})

I really get an error message https://prnt.sc/r8iejl But this message is from the code, in this case 401 and not the custom message "Incorrect authorization token."

And when I try to give response.body.message or response.message I get undefined, I am not able to receive my error code. I've tried return res.status(401).json({message: "Incorrect authorization token"}) but I get the status error code again


Solution

  • I was getting the same issue. If I sent res.status(401).json({message: "Incorrect authorization token"}) I would get back You do not have permission to view this directory or page.

    My issue was I was running nodejs through IIS using iisnode. IIS by default replaces any error message you send. This behavior can be turned off by using adding the following code to your web.config file under <system.webServer> (source):

    <httpErrors existingResponse="PassThrough" />

    After restarting the server, I was able to get {message: "Incorrect authorization token"} back instead.