Headers cannot be modified after they have been sent to the client in Node.js and Angular

I am working on developing login and registration services using Nodejs Express. Every time I make a request in postman, I consistently encounter the same error:

https://i.stack.imgur.com/QZTpt.png

Interestingly, I receive a response in postman (registering, logging in, and even receiving my JWT token), but after each request, I find myself unable to do anything without restarting the service in my terminal.

The code snippet from my index.ts file:

 import express from "express";
 const https = require("https");
 import cors from "cors";
 import mongoose from "mongoose";
 const app = express();

 //import routes
 const usersRoute = require("./routes/users");

 //Middleware
 app.use(cors());
 app.use(express.urlencoded({ extended: false }));
 app.use(express.json());

 //route midddlewares
 app.use("/api/users", usersRoute);

 //connect to db
 mongoose
   .connect("mongodb://localhost:27017/loginregister")
   .then(() => {
     console.log("connected to database");
   })
   .catch(() => {
     console.log("connection failed!");
   });
 const PORT = 3000;
 app.listen(PORT, () => console.log(`Server up and running on port ${PORT}`));

The snippet from my users.ts file:

 ...
(code continues here with details about registering and logging in users)
 ...

The content of verifyToken.ts file is as follows:

 ...
(code for verifying tokens for authentication purposes)
...

In my Angular frontend code, specifically in login.component.ts:

 ...
(angular code related to handling form submission and user login)
...

And the error encountered on the web application is shown below: https://i.stack.imgur.com/UmKzo.png

SOLVED: The initial error regarding setting headers after they have been sent to the client was resolved by following the solution provided by Shivam Sood. Additionally, the second error reported in the browser's console was fixed by specifying responseType: 'text' in the http.post() request within my auth.service.ts file.

Answer №1

An error is originating from this particular line within your login route

The issue lies with the following code:
res.header("auth-token", token).send(token);
res.send("Logged in!");

You are making a mistake by sending the response twice using res.send()

To address the problem, you must remove

res.send("Logged in!");
.

UPDATE

It seems that the problem may be related to Angular expecting JSON data by default, whereas your backend is sending text data. This mismatch is causing the parsing to fail.

To resolve this, you should modify res.send to

res.header("auth-token", token).json({token});

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

The Core.js file seems to be missing, but it can be found in the node modules directory. The Meteor client is functioning properly, but there seems to be

I encountered an issue while trying to import the meteor-client.js file. The problem arose when loading ecmascript-runtime-client, which prompted me with an error stating that the core-js npm package could not be found in my node_modules directory. Even af ...

Role reactions in Discord.js are a useful feature that allows users

Whenever this code is executed, an error message is displayed. The bot has full administrative privileges over the server where I am testing it. client.on('messageReactionAdd', async (reaction, user) => { if (reaction.message.partial); awa ...

Generate a div element dynamically upon the click of a button that is also generated dynamically

Putting in the effort to improve my Angular skills. I've found Stack Overflow to be extremely helpful in putting together my first app. The service used by my app is located in collectable.service.ts: export class CollectableService { private col ...

Empowering your Angular2 application with data binding

I am currently working with the following template: <table width="700"> <caption>All Users</caption> <thead> <tr> <th>name</th> <th>surname</th> < ...

I am encountering an error with an Unhandled Promise Rejection, but I am unable to determine the reason behind it

const express = require('express'); const cors = require('cors'); const massive = require('massive'); const bodyParser = require('body-parser'); const config = require('../config'); const app = express(); ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Error: Unable to access the 'then' property of an undefined object when working with promises

I'm developing a website project that serves as a "Walmart" version of AirBnB. Here's the functionality of the button in question: When a user clicks on the "Make Reservation" button on a listing, they are prompted to select a start and end dat ...

Having trouble sending a PDF attachment with more than two photos through SendGrid

I encountered a strange issue with my API. The API I created allows users to upload photos to the server, save data to the database, generate a PDF with the data and photos, and send an email with the PDF attachment. Everything was working perfectly when I ...

Returns false: CanActivate Observable detects a delay during service validation

Issue with Route Guard in Angular Application: I encountered an issue with my route guard in my Angular application. The problem arises when the guard is active and runs a check by calling a service to retrieve a value. This value is then mapped to true or ...

How can I display a route from the starting point to the destination with all markers on a Leaflet map, using latitudes and longitudes from an API in Angular

Let's consider a scenario where we have a single bus with a fixed route, and all the bus stops along that route are marked. How can we achieve this in Angular using Leaflet maps as shown in the following image https://i.stack.imgur.com/GgEPS.png ...

Is there a way to retrieve the latitude and longitude values using a plugin and then make a web service call in Ionic with Angular 5?

I am currently trying to retrieve the latitude and longitude coordinates of a location by using geocode in Angular 5 within the Ionic framework. Once I have obtained the lat long, I intend to pass it to my service. The issue I am facing is that my service ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

Despite being present in the node_modules folder, the ag-grid-vue module appears to be missing

Currently, I am diligently following the Vue.js AgGrid getting started tutorial step by step: https://www.ag-grid.com/vuejs-grid/ However, upon adding the <script> section and saving my progress, an error promptly appears: ERROR Failed to compile ...

Guide to iterating through different endpoints in a predetermined sequence

I am facing a challenge with testing various endpoints using different login credentials. When looping through the endpoints, the results are not appearing in the sequential order due to asynchronous nature. My goal is to iterate through each endpoint wit ...

Ways to incorporate only essential UI elements in @angular/material

In the process of creating my Angular application, I am looking to streamline its size. Currently, my app relies on Angular Material, but upon inspecting the node_modules folder, I realized that there are unused UI components such as autocomplete and check ...

Setting up a node application on Digital Ocean using PM2 for deployment

As I attempt to direct a domain to my node app, I realize that it utilizes port 80 and I am experimenting with PM2 to launch my node app as a service. When I input pm2 start app.js, I receive a series of incomprehensible characters that appear like this: ...

Experiment with AngularJS and Jasmine by utilizing the stand-alone command line interface for testing

I have been working on a basic .js file and testing it with Jasmine. The tests run smoothly when using Jasmine's SpecRunner.html. However, I was wondering if it is possible to achieve the same results through a command line interface. I do have node ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Finding a way to compare the input from `process.stdin` with a string in Node.js

I came across a solution at the provided link, but even after implementing the suggested code changes, it still doesn't work as expected. The output only contains the data without the log message inside the if statement. I have also attempted using to ...

Best practices for securing your App/API endpoints

I am currently in the process of developing a mobile app (using Ionic/Cordova) that will interact with an API built with NodeJS. As I navigate through this project, I find myself contemplating how to implement a user authentication method that serves dual ...