Unable to send headers to the client in expressjs as they have already been set

After successfully logging in, I am trying to redirect to another page but keep encountering the error message "Cannot set headers after they are sent to the client". I understand that I need to place the res.redirect method somewhere else in my code, but I am struggling to figure out the right placement.

router.get('/login',(req,res)=>{
    res.render('login')
})
router.post('/login',(req,res)=>{
    user.findOne({
        where: {
            userName : req.body.userName
        }
    })
    .then(userInfo=>{
        if(userInfo){
            if(bcrypt.compareSync(req.body.password,userInfo.password)){
                const token = jwt.sign(userInfo.dataValues,process.env.SECRET_KEY,{
                    expiresIn:1440
                })

               res.send(token)
               res.redirect('/home')

            }

            else {
                res.status(400).json({error:'user doesnt exist'})
            }


        }
    }
    )
})

Answer №1

res.redirect is essentially a shortcut for setting the redirect status to 302 and adding a Location header. If you want, you can simplify this by:

res.setHeader('Location', '/home');
res.send(token);

However, consider if res.send(token) is really what you need. It may be more appropriate to include a Set-Cookie header in the response from /login. In that case, you could try:

res.setHeader('Set-Cookie', `token=${token}`);
res.redirect('/home');

Alternatively, perhaps your server shouldn't handle the redirect at all. If you are sending the token back to the client, maybe it should be responsible for setting the token in the document cookie and handling the redirect on the client-side like this:

/* This code runs in the browser after receiving the token, not on the server */

document.cookie = `token=${token}`;
window.location.href = '/home';

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

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...

Show only the selected option with jQuery's on change event and disable or remove the other options

My goal is to make it so that when a user selects an option from a dropdown menu, the other options are disabled or hidden. For example, if option "1" is selected, options "2", "3", and "4" will be removed: <div class="abc"> <div class="xyz"> ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Error message: NodeJS informs you that the requested file could not be found

Just diving into the world of NodeJS, I find myself faced with a challenge on my login page. My goal is to validate users using a form submission. I decided to intercept the form submission and send an ajax request to my server (app.js) file. However, all ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

Execution of Ajax call fails to occur synchronously

I have created a unique weather website that utilizes the flickr API as well as the yahoo API to gather weather data. However, I am facing an issue where the ajax call from the yahoo API does not retrieve the necessary data in time for the content of the p ...

Issue with electron-vue: Unable to modify Vuex state when using RxJS subscribe

I need help with my code involving two functions in the mutations and two pieces of state const state = { files: [], uploadProgress: 0 } const mutations = { SET_UPLOAD_IMAGE: (state, files) => { state.files = files }, UPLOAD_IMAGE: ( ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

Tips for transferring the id from a delete button to a delete button in a popup dialog box

In my frontend application, there is a table where each row corresponds to an item. For every row, there is a "Remove" button that triggers a warning popup upon being clicked. The intention is to pass the item's ID in this popup so that if the user co ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Utilize node.js to run a local .php file within a polling loop

Here is the purpose of my application in brief. I am using a PHP file to read data via an ODBC connection and then write that data to a local database. This PHP file needs to be executed LOCALLY ON THE SERVER every time a loop is processed in my node.js, ...

What could be the reason behind Cors preventing my API request?

Currently, I am in the process of developing a project that requires me to access an API that I have created. const endpoint = 'localhost:3000/api/v1/'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'appl ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

Find a way to incorporate social media features into a web application that functions intermittently

Currently, I am in the process of developing a social media app and working on integrating a search feature to enable users to find friends. The code I have below seems to be functional at times but not consistent (quite frustrating!) The issue seems to st ...

Using JQuery to enable the movement of divs on a screen through clicking and dragging, without the use of

Recently, I've been experimenting with a small project involving draggable divs. However, the code I've written doesn't seem to be functioning properly, causing JQuery to become unresponsive. Is there an alternative method that is simple an ...