2

I am trying to redirect from the condition of a mysql to a get method but it does not work. How could I solve it?

app.post('/responses/',(req,res)=>{
    var {text, context ={} } = req.body;
    var params = {
        input: {text},
        workspace_id: '07',
        context
    }`
    `assistant.message(params,(err,response) => {
        if(err){
            res.status(500).json(err);
        }
        else {
            res.json(response);
            console.log(JSON.stringify(response, null, 2));
        }
        if(response.context.rfc){
            var RFC = response.context.rfc;
            connection.connect(function(err) {
                if (err) throw err;
                connection.query(`SELECT * FROM test where RFC = '${RFC}'`, function (err, result, fields) {
                    if(result.length){
                        console.log("login");
                    }
                    else {
                        console.log('no login');
                        res.redirect('/home'); //Her not redirect.
                    }
                });
            });
        }
    });
});

Because show this error: hrow err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Isaac Alejandro
  • 247
  • 1
  • 3
  • 8
  • 1
    Please expand on *"it does not work"* with a [mcve]. – jonrsharpe Dec 26 '18 at 23:21
  • 1
    per [https://stackoverflow.com/questions/38810114/node-js-with-express-how-to-redirect-a-post-request] , change redirect to `res.redirect(307, '/home');` – Uma Dec 26 '18 at 23:34
  • @Uma not work. The console show: `throw err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client` – Isaac Alejandro Dec 26 '18 at 23:37

1 Answers1

0

The error message indicates you are trying to set headers after the response is already sent. From your sample code, looks like your API call (whatever assistant.message is) is returning RFC. You then attempt to redirect to another page, but you've already called res.json, which begins sending a response to the browser.

You need to refactor your controller a bit so that you only call res.redirect or res.json, not both.

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44