question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

res.redirect error

See original GitHub issue

Question

Hello guys I get an error while doing res.cookie and res.redirect in the success message.

My Code:

const loginPageShow = async (req, res, next) => {

    try {
        const youtube = await new Innertube();

        var creds = '';


        youtube.ev.on('auth', (data) => {

            if (data.status == 'AUTHORIZATION_PENDING') {

                res.render('user/Login', { layout: '../layouts/General', title: `Youtube Abone Hilesi`, description: ``, keywords: ``, data })

            } else if (data.status == 'SUCCESS') {
                

                function credsSend() {

                    return creds = data.credentials;
                }
                credsSend()

                         const datax = {
                             time: Date(),
                             userId: data.credentials.access_token,
                         }
                         const jwtToken = jwt.sign(datax, process.env.JWT_SECRET_KEY, { expiresIn: '1d' });
             
                         res.clearCookie('access_token');
             
                         res.cookie('access_token', jwtToken, { expires: new Date(Date.now() + 900000) })
                         //console.log(req.cookies.access_token);
                         res.redirect(`https://twitter.com`);

            }

        });


        await youtube.signIn(creds);


       async function check() {

            const uyeVarMiFilter = { channel_id: (await youtube.account.getInfo()).channel_id };
            const uyeVarMi = await User.find(uyeVarMiFilter).countDocuments();
            if (uyeVarMi > 0) {
                //const delUser = await User.findOneAndDelete({ channel_id: (await youtube.account.getInfo()).channel_id })
                const guncelBilgiler = {
                    name: (await youtube.account.getInfo()).name,
                    email: (await youtube.account.getInfo()).email,
                    channel_id: (await youtube.account.getInfo()).channel_id,
                    subscriber_count: (await youtube.account.getInfo()).subscriber_count,
                    photo: (await youtube.account.getInfo()).photo[0].url,
                    access_token: creds.access_token,
                    refresh_token: creds.refresh_token,
                    expires: creds.expires,
                }
                await User.findOneAndUpdate(uyeVarMiFilter, guncelBilgiler)
            } else {
                const filter = { access_token: creds.access_token };

                const newUser = new User({
                    name: (await youtube.account.getInfo()).name,
                    email: (await youtube.account.getInfo()).email,
                    channel_id: (await youtube.account.getInfo()).channel_id,
                    subscriber_count: (await youtube.account.getInfo()).subscriber_count,
                    photo: (await youtube.account.getInfo()).photo[0].url,
                    access_token: creds.access_token,
                    refresh_token: creds.refresh_token,
                    expires: creds.expires,
                    tActive: '1'
                });
                await newUser.save();
            }
        } check(); 

    } catch (error) {
        console.log(error);
    }



}

Error Code:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/Users/canyesilyurt/Desktop/ytPanel/node_modules/express/lib/response.js:794:10)
    at ServerResponse.append (/Users/canyesilyurt/Desktop/ytPanel/node_modules/express/lib/response.js:755:15)
    at ServerResponse.res.cookie (/Users/canyesilyurt/Desktop/ytPanel/node_modules/express/lib/response.js:884:8)
    at ServerResponse.clearCookie (/Users/canyesilyurt/Desktop/ytPanel/node_modules/express/lib/response.js:827:15)
    at EventEmitter.<anonymous> (/Users/canyesilyurt/Desktop/ytPanel/src/controllers/homeController.js:45:30)
    at EventEmitter.emit (node:events:532:35)
    at Timeout._onTimeout (/Users/canyesilyurt/Desktop/ytPanel/node_modules/youtubei.js/lib/core/OAuth.js:120:18)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

Other details

No response

Checklist

  • I am running the latest version.
  • I checked the documentation and found no answer.
  • I have searched the existing issues and made sure this is not a duplicate.
  • I have provided sufficient information.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
MasterOfBob777commented, Jul 30, 2022

(Also just a little tip, refactoring your getInfo() calls into a single variable will most likely improve your performance drastically and might even help some issues you might encounter down the line, because each call does a network request)

0reactions
devcycodecommented, Jul 30, 2022

Is it possible to access data.code without using this function?

youtube.ev.on('auth', (data) => {
      switch (data.status) {
        case 'AUTHORIZATION_PENDING':
          console.log(`
                Hello! On your phone or computer,
                go to ${data.verification_url} and enter
                the code ${data.code}.
              `);
              next();
          break;

          case 'SUCCESS':
            console.log('bbbb');
          break;
      }
    });
Read more comments on GitHub >

github_iconTop Results From Across the Web

Send error message on redirect - node.js - Stack Overflow
If the credentials are incorrect, I want to redirect the user to /login with an error message along the lines of "incorrect username...
Read more >
Express.js res.redirect() Function - GeeksforGeeks
The res.redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which ...
Read more >
How to redirect with error message in express.js : r/node - Reddit
How to redirect with error message in express.js ... const router = require('express').Router(); router.get('/sayhello',(req,res) => { res.render( ...
Read more >
express.Response.redirect JavaScript and Node.js code ...
Best JavaScript code snippets using express.Response.redirect(Showing top 15 results out of 5,499) · index.js/app.use · biz/webui/lib/index.js/app.all · server.js/ ...
Read more >
res.redirect() - Sails.js
Redirect the requesting user agent to the given absolute or relative URL. Usage. # return res.redirect(url);. Or: return res.redirect(statusCode, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found