Error: Unauthorized access request occurs when the user does not exist in the database

Currently, I am working on implementing a basic login system using express sessions. However, I have encountered an issue where I receive an "Invalid status code" message when the user is not found in the database.

I am aiming to set it up so that if the user cannot be found in the database, the client is redirected to a specific route. Unfortunately, instead of being redirected, an error is thrown.

The system functions flawlessly when a user is found with no bugs present.

If anyone could offer guidance on resolving this problem, I would greatly appreciate it!

Login Route

//@ROUTE: Login Route
//@DESCRIPTION: Displays the login page
app.get('/login', (req, res)=> {
    res.render('login.ejs', {title: "Login :: Clipit", curSession: req.session})
})

Login Post

//@ROUTE: Login Post
//@DESCRIPTION: Searches for the user in the database and logs them in (establishes a new session)
app.post('/api/login', (req, res)=> {
    const username = req.body.inputUsername
    const password = req.body.inputPassword

    userDB.findOne({username: username, password: password}, (err, result)=> {
        if(err) {
            throw err;
        } else if(!result) {
            res.redirect('/login-error', {curSession: req.session})
        } else {
            req.session.username = result.username
            req.session.loggedIn = true
            console.log(`${req.session.username} has logged in.`)
            res.redirect('/')
        }
    })
})

Bug:

express deprecated res.redirect(url, status): Use res.redirect(status, url) instead server.js:185:17
node:events:346
      throw er; // Unhandled 'error' event
      ^

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: { curSession: [Session] }
    at new NodeError (node:internal/errors:329:5)
    at ServerResponse.writeHead (node:_http_server:282:11)
    at ServerResponse.writeHead (C:\Users\gabri\Desktop\clipit\node_modules\on-headers\index.js:44:26)
    at ServerResponse._implicitHeader (node:_http_server:273:8)
    at writetop (C:\Users\gabri\Desktop\clipit\node_modules\express-session\index.js:276:15)
    at ServerResponse.end (C:\Users\gabri\Desktop\clipit\node_modules\express-session\index.js:356:16)
    at ServerResponse.redirect (C:\Users\gabri\Desktop\clipit\node_modules\express\lib\response.js:951:10)
    at C:\Users\gabri\Desktop\clipit\server.js:185:17
    at C:\Users\gabri\Desktop\clipit\node_modules\mongoose\lib\model.js:4870:18
    at processTicksAndRejections (node:internal/process/task_queues:76:11)
Emitted 'error' event on Function instance at:
    at C:\Users\gabri\Desktop\clipit\node_modules\mongoose\lib\model.js:4872:15
    at processTicksAndRejections (node:internal/process/task_queues:76:11) {
  code: 'ERR_HTTP_INVALID_STATUS_CODE'
}
PS C:\Users\gabri\Desktop\clipit>

Answer №1

Two issues have been detected in your console:

The Warning:

express deprecated res.redirect(url, status): Use res.redirect(status, url) instead server.js:185:17.
The warning is related to the ordering of parameters in the code snippet provided. The correct order for the res.redirect() function is status followed by url.

You cannot include an object as a parameter. Only a status code and a path are allowed. Consider using either

res.render('/login-error', {curSession: req.session})
or simply res.redirect('/login-error'), depending on your specific requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a new object to a mongoDB collection using its unique id

I have a collection named Users where user messages and information are stored. My goal is to add new objects to the existing collection based on their id. When trying to perform this action, I encounter an error 'TypeError: user.insert is not a func ...

Exploring the power of Mongoose's aggregate pipeline with nested object lookup

Let me discuss an issue I am facing with you. I have 3 different entities that I need to access in my query: Evaluation: [ { _id: 1, questionary: 1, subject: 1 }, { _id: 1, ...

Necessary within a JavaScript Class

As a newcomer to using classes in JavaScript, I've been exploring the best practices and wondering about how 'requires' work when used within a class. For example, let's say I want to craft an IoT Connection class for connecting to the ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

An Easy Method for Managing Files in a Node.js Directory: Editing and Deleting Made Simple

Greetings! I am currently in the process of developing a basic blog using express.js. To manage the creation, updating, and deletion of posts based on their unique id, I rely on a data.json file. For each action performed, I utilize fs.writeFile to generat ...

Issues with intellisense while working on node.js projects in Visual Studio 2017

Typically, we work in a Microsoft stack development environment, but for this particular project, we are required to develop using Node.js in Visual Studio 2017. Some aspects of this setup are causing us frustration and confusion. We installed the Node.js ...

Using JSON data in an ArrayBuffer with TypeScript

I am currently struggling with converting the received ArrayBuffer data from a server via Websocket into another format. Below is the WebSocket code snippet: let ws = new WebSocket('wss://api.example.com/websocket'); ws.binaryType = 'arrayb ...

I'm encountering an issue in my server.js file where I am unable to read the property 'collection' as it is undefined

I have encountered an error in my code: /home/ubuntu/workspace/server.js:43 db.collection('quotes').find().toArray(function(err, results) { ^ TypeError: Cannot read property 'collection' of undefined at Object.<anonymous> ( ...

Is it possible to use bearer token authentication when Access-Control-Allow-Credentials is set to false?

My customer authenticates their requests using the header below: Authorization: Bearer some-token If I add this header to my responses, will it cause any issues? Access-Control-Allow-Credentials: false ...

What is the best way to utilize node modules in the client-side while developing an Express application?

I'm currently working on a project with intl-tel-input integration within an environment utilizing express and ejs. In my app.js, I have configured app.use(express.static(path.join(__dirname, 'public')));, which allows Express to serve all ...

Efficiency of Promise-based parallel insert queries in MySQL falls short

I have developed a code in Node.js to execute insert queries using Promise.js but unfortunately, I am encountering an exception stating "Duplicate Primary Key" entry. Here is the snippet of the code: var Promise = require("promise"); var mySql = requir ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

How can I simulate an fs.readdirSync function call in Jest while incorporating withFileTypes, utilizing filter and map?

In Jest, I am trying to figure out how to mock the fs.readdirSync method within this function. export const getDirectoryFiles = async (directory) => { return fs .readdirSync(directory, { withFileTypes: true }) .filter(dirent => !dirent.isDirect ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

Do the variables declared in app.js have scope access to the functions within routes, in the context of Express and node.js?

While working with express js, I came across an interesting situation. In my app.js file, I had declared the following: var mongoose = require ('mongoose'); var db = mongoose.connect('mongodb://localhost/testdb'); Next, in my /mo ...

Guide to upgrading nodejs from version 6.x to 8.x

Need help updating nodejs from version 6.x to 8.x on Ubuntu 16.04. Should I uninstall the old version and install the new one? If so, how can I accomplish this? I attempted using 'sudo n latest' but received a 'sudo: n: command not found&apo ...

Issue with ElectronJs: HelloWorld application failing to launch

I've recently embarked on creating a simple hello world application with Electron JS, following the steps outlined in the official Electron tutorial. Each step has been meticulously executed as instructed. The process involved the creation of 3 esse ...

What causes the condition to be disregarded within the "if" statement?

Postman is showing an error message "error login" instead of the expected result "success" when running this server. However, when I include console.log(body.req), I see "name, email, password" in the terminal, which are passed in the body. Additionally, ...

Is there a similar alternative to ignoring in webpack or browserify?

My code works perfectly in the browser after ignoring two packages with browserify: browserify files.js -i fs-extra -i request --standalone files > files.browserify.js. However, when I try to use webpack instead, the code throws errors about missing mod ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...