TransWikia.com

Express: Cannot set headers after they are sent to the client

Stack Overflow Asked on December 27, 2021

I am trying to learn Web APIs. I was writing a simple code that gets data from the server in the log after clicking a button, but I keep getting an error in the server side, which is "Cannot set headers after they are sent to the client".

My server side code:

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
projectData = [];

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cors());
app.use(express.static("website"));

const port = 9013;
const server = app.listen(port, listening);

function listening  () {
    console.log("running localhost"+port);
}
let someData = {name:"name", num:"num"};
app.get ('/hello', function (req, res){
    res.send("Get request response");
    res.send(someData);
})

my client side code is:

const generate = document.getElementById("generate");

generate.addEventListener("click", performAction);

function performAction (e) {
    getDemo();
}

const getDemo = async () => {
    const res = await fetch ("/hello");
    try {
    const data = await res.json();
    console.log(data);
    }
    catch (error) {
        console.log("erroor");
    }
}

Thanks for helping.

One Answer

That problem is something very basic. Here:

app.get ('/hello', function (req, res){
    res.send("Get request response");
    res.send(someData);
})

You cannot send a second response back. You already sent Get request response back to the client.

1 request = 1 response from server. Thats all. Remove 1 line:

app.get ('/hello', function (req, res){
    res.send(someData);
})

Bonus: Just a hint, you should put your fetch inside the try / catch block not outside.

Answered by Ifaruki on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP