1

My code is

main.post('/userlist', function(req, res, next) {
    // where did you get this?
    // var db = req.db;
    var query = connection.query("SELECT name,zaman,giriscikis FROM giriscikis where date_format(zaman,'%Y-%m-%d') between ? and ?", [req.body.bas, req.body.bitis], function(err, result) {
        if (err) throw err;

        console.log(result);

        res.send(httpResponse(result));
        return res.redirect('/zamansorgu');

        //console.log(req.body.bas)
        //console.log(req.body.bitis)
    });
});

I want to fecth data from database and redirect to same page in the code(zamansorgu.html)

But I get an error

Cannot set headers after they are sent to the client

How can I solve this problem

thank you for your helps

Molda
  • 5,619
  • 2
  • 23
  • 39
asuscu
  • 225
  • 1
  • 3
  • 13
  • 1
    Does this answer your question? [Using Express.js and NodeJS, Can you send JSON via redirect in the response body](https://stackoverflow.com/questions/21418945/using-express-js-and-nodejs-can-you-send-json-via-redirect-in-the-response-body) – eol Jun 10 '20 at 07:00
  • You cannot use res.send and res.redirect at the same time. You can only use one or the other. Once you call res.send the connection will close so calling res.redirect afterwards will not work since the client has disconected. – Molda Jun 10 '20 at 07:04

3 Answers3

3

You are attempting to send back JSON data and redirect to a different page. That's not possible. Each endpoint request can have one response, not more. You can either send back the data, or redirect. That's because redirecting really does send back data too (the html of the new target page).

Think about it from the caller's point of view. If it did allow this how would it work? If someone uses this link from a browser should the browser show the JSON data you returned, or should it take the user to the new page?

The error is saying "hey, I already sent back data. I can't redirect now because we are already down the path of returning some JSON".

If you want to use the data to format the output that can be done, or if you want to redirect to a new location and pass the data in the url, that's also possible. Consider code like this:

main.post('/userlist', function(req, res, next) {
    // var db = req.db;
    var query = connection.query("SELECT name,zaman,giriscikis FROM giriscikis where date_format(zaman,'%Y-%m-%d') between ? and ?", [req.body.bas, req.body.bitis], function(err, result) {
        if (err) return next(err);

        if (result.urlparam) {
          // this builds a new url using the query value
          const nextUrl = `/zamansorgu?param=${result.urlparam}`;
          return res.redirect(nextUrl);
        }
        else {
          // this builds html here
          const html = `<html><body><h1>${result.title}</h1></body></html>`;
          return res.send(html);
        }
    });
});
Always Learning
  • 5,510
  • 2
  • 17
  • 34
0

I also ran into this, in my case it was quite a deceptive little bug. A node-inspector session helped me pinpoint the problem quickly however. The problem in my case was pretty bone-headed, the res.end call in the sample below is the offending line.

res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(someObject));

someObject did not exist after a refactor and that was causing a ReferenceError to get thrown. There is a try-catch in Router.prototype._dispatch that is catching the ReferenceError and passing it into next

Vaishali Tekale
  • 101
  • 2
  • 2
0
res.status(301).redirect(`/zamansorgu?name=${"John"}&email=${"john@email.com"}`)

So, this is something I explored but it will be dependent on the structure of your application. You could always pull the data out using query params and hydrate your application.

Mbiplang Ardel
  • 546
  • 5
  • 18