Attempting to send headers after they have already been sent to the client is not permitted when using response.json()

Trying to set up an API to retrieve data, but encountering a problem with the res.json() function. The error message is as follows:

web_1         | Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
web_1         |     at ServerResponse.setHeader (_http_outgoing.js:533:11)
web_1         |     at ServerResponse.header (/mbs_welfare/node_modules/express/lib/response.js:771:10)
web_1         |     at ServerResponse.send (/mbs_welfare/node_modules/express/lib/response.js:170:12)
web_1         |     at /mbs_welfare/server.js:45:9
web_1         |     at Layer.handle_error (/mbs_welfare/node_modules/express/lib/router/layer.js:71:5)
web_1         |     at trim_prefix (/mbs_welfare/node_modules/express/lib/router/index.js:315:13)
web_1         |     at /mbs_welfare/node_modules/express/lib/router/index.js:284:7
web_1         |     at Function.process_params (/mbs_welfare/node_modules/express/lib/router/index.js:335:12)
web_1         |     at next (/mbs_welfare/node_modules/express/lib/router/index.js:275:10)
web_1         |     at Layer.handle_error (/mbs_welfare/node_modules/express/lib/router/layer.js:67:12)

l

router.get('/profile/user/me', async (req, res, next) => {
    let user = req.session.user;
    if(user) {
        try {
            let me = user.adminID
            let info = await knex('admin_accounts').where('adminID', me)
            res.json(info)
        } catch (e) {
            console.log(e);
        }
        res.sendFile(path.join(__dirname + '/../public/personal_information.html'));
    }else{
         res.redirect('/');
    }
});

Answer №1

The reason for this error is that the variable res is being invoked multiple times in your code, specifically:

res.json(info) - here and then

res.sendFile - also here, for instance

You must ensure that res is only called once at a time.

To clarify, only one response should be sent per request.

I hope this explanation helps you resolve the issue.

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

Pandas: Transforming JSON files with style

I have a collection of JSON files that are somewhat messy and I need to convert them into Excel files with a specific format. I've managed to decode everything into a pandas dataframe, but my current code only handles integer data types and not string ...

"Embed a filter in the loopback framework prior to sending a GET request

I've integrated Loopback into my Node.js app for generating the CRUD API automatically. I needed to customize one of the GET APIs to include a table as well. The typical way to achieve this is by adding an include filter in the query like: /api/expen ...

Assistance with utilizing Google Sheets scripts for retrieving formulas is needed

I've been working on a small search tool in Google Sheets as a personal project to improve my skills and knowledge of GS. Munkey has been guiding me over the past few weeks and helping me develop my understanding. Below are the links to my "Database" ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Encountering the error message "Unexpected token. Did you mean {'>'} or >?" when trying to use an arrow function in React

I recently started learning React and Javascript. I encountered an error message that said: "Unexpected token. Did you mean {'>'} or >?", specifically in relation to the "=>" part of the code below. This issue arose while I was worki ...

What is the method for identifying the environment within an Express.js application?

Is there a reliable method for determining the environment in which an expressJS app is currently operating (development, test, production)? I have checked process.env, but found no clear indication of the environment. I know that variables can be set in ...

I am eager to run the code that I retrieved from the server. I have access to the code in my console and I desire for it to execute on the main browser page

Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script fro ...

Unable to serialize stream data in ASP .NET Core

Attempting to deserialize objects from an HTTP response. The response stream contains JSON information, which has been verified as valid through an online deserializer. I obtained the object class from the API framework, so I believe all properties should ...

Adding pointlights to the camera in three.js is a great way to

I have written some code to add two lights on the camera that move along with the orbitcontrols. However, the lights and spheres are not visible for some reason. Can someone help me identify the issue in my code? var sphere1 = new THREE.Mesh( new THREE.Sp ...

Combining data from two MongoDB collections with JSON arrays

I have experience writing queries for simple single key-value joins using $lookup, but I am facing a more complex scenario now and unsure how to tackle it. product : { "_id": ObjectId("6200a77598412e443c03f0ee"), "name&quo ...

Changes to a Vue shallowRef's value do not automatically trigger an update

I created a simple program to test out shallowRef and encountered an unexpected behavior. The instructions mention that the first method of updating should work, but only the second one seems to update the value properly. Why is that? Below is my code sni ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

Transform an array list of strings into an array list of integers

I am working with a Model class called ModelWeeklyGuarantee and I need to convert a string ArrayList to an integer ArrayList For example, converting [5,7,9] from a string ArrayList to [5,7,8] in an IntegerArrayList at index 0. public static ArrayList< ...

Tips for generating a shared message thread among multiple users

Imagine a scenario with two users: user1 sends a message to user2. When user2 logs in, they will find a message from user1 in their inbox. const MessageSchema = new Schema({ subject: String, body: String, seen: Boolean, sender: { type: mongoo ...

Guide on generating a fresh array of objects that encompass distinct items, alongside their combined prices and quantities using JavaScript

I am struggling to generate a new array of objects from one that contains duplicates. For instance, here is the console.log output of the current array: console.log(items); [{ _id: 5eb2f7efb5b8fa62bcd7db94, workName: 'best item ever', ...

What is the best way to implement slideToggle functionality (using JavaScript) for a specific element within a foreach loop?

When I click on a specific product, I want to display the description of that product. However, with my current code, every time I click on any product info, it shows me all the descriptions of all products. Can someone please help me fix this issue? ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...

Distinctive Tags Nodes within a Huffman Hierarchy

I'm currently developing a Python application that can compress and decompress text files using a Huffman tree structure. In the past, I saved the frequency table in a .json file alongside the compressed data. When reconstructing the decompression tre ...

Encountered an error while attempting to minify code during the npm run build

After completing my react application using create-react-app , I encountered an issue when trying to build it with npm-build. While there were no problems running it locally with npm start, I faced an error during minification of the code. I attempted ...

Notification for Pinned Tabs Update

Is there a method to emphasize pinned tabs in web browsers when receiving new notifications similar to Gmail, Facebook, or Twitter? The attached image should provide clarity on my query. I am seeking a solution that works across all browsers. ...