简体   繁体   English

我如何在服务器响应中设置 cookie 和 json 并重定向到客户端 url/PassportJS NodeJS

[英]How i can set cookie and json in server response and redirect to client url/ PassportJS NodeJS

Me need set cookie with httlp only in server with using passport js ("Google"), after i set cookie me need redirect but i can't i see this error:我只需要在使用护照 js(“谷歌”)的服务器中使用 httlp 设置 cookie,在我设置 cookie 之后我需要重定向但我看不到这个错误:

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 (H:\1HF_solution\location\server\node_modules\express\lib\response.js:794:10)
    at ServerResponse.location (H:\1HF_solution\location\server\node_modules\express\lib\response.js:915:15)
    at ServerResponse.redirect (H:\1HF_solution\location\server\node_modules\express\lib\response.js:953:18)

I can only set cookie or redirect but i need both.我只能设置 cookie 或重定向,但我需要两者。 Help please Here my code google-strategy.ts请帮助我的代码 google-strategy.ts

import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import { IGoogleDto } from '../interfaces/user-interface';
import userService, { IServerData } from '../service/user-service';

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: '/api/oauth/google/callback',
    },
    async function (
      accessToken: any,
      refreshToken: any,
      profile: { _json: IGoogleDto },
      done: (arg0: any, arg1: boolean | IServerData | { registrationToken: string }, arg2: undefined) => void
    ) {
      try {
        const googleDto: IGoogleDto = profile._json;

        const result = await userService.findOrCreateForGoogle(googleDto);
       'result: {refreshToken:'',userDto:'user data object'}

        done(null, result, null);
      } catch (err) {
        done(err, null, null);
      }
    }
  )
);

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((user, done) => {
  done(null, user);
});

oauth-router.ts oauth-router.ts

import { Router } from 'express';
import passport from 'passport';
import { IRTRequest } from '../interfaces/user-interface';
import { IServerData } from '../service/user-service';
require('../strategy/google-strategy');

const router = Router();

const CLIENT_URL = process.env.CLIENT_URL;

router.get('/logout', (req, res, next) => {
  req.logout(function (err) {
    if (err) {
      next(err);
    }
  });
  res.clearCookie('refreshToken');
  res.redirect(CLIENT_URL);
});

router.get('/google/success', (req: IRTRequest, res, next) => {
  if (req.user) {
    res.status(200).json({
      success: true,
      message: 'successfully',
      user: req.user,
    });

    res.cookie('refreshToken', req.user.refreshToken, {
      maxAge: 30 * 24 * 60 * 60 * 1000,
      httpOnly: true,
    });
  }
});

router.get('/google/failed', (req, res) => {
  res.status(401).json({
    success: false,
    message: 'failure',
  });
});

router.get(
  '/google/callback',
  passport.authenticate('google', {
    successRedirect: 'success',
    failureRedirect: 'failed',
  })
);

router.get('/google', passport.authenticate('google', { scope: ['email', 'profile'] }));

In client i call在客户端我打电话

  const GoogleHandler = () => {
    window.open(process.env.REACT_APP_GOOGLE_OAUTH_URL, '_self');
  };

I try use router.get(url,(req,res)=>{我尝试使用 router.get(url,(req,res)=>{

router.get('/google/callback', async (req: IRTRequest, res, next) => {
  return await passport.authenticate(
    'google',
    {
      successRedirect: 'login/success',
      failureRedirect: 'failed',
    },
    async (err, data: IServerData) => {
      'set cokkie here and redirect but i have error'
    }
  )(req, res);
});

Also i try end() but i stay in server url.我也尝试 end() 但我留在服务器 url 中。

PS I sovled this problem. PS 我解决了这个问题。 For avoid this situation i use cookie, and set my userData and set maxAge 5 minutes, this is not secret info and after this 5 minutes thei will cleared and no one get read this data, but if someone can it is not a problem.为避免这种情况,我使用 cookie,设置我的 userData 并设置 maxAge 5 分钟,这不是秘密信息,5 分钟后它们将被清除,没有人可以读取此数据,但如果有人可以,这不是问题。 In client i just read my cookie and set data using redux-tookit在客户端,我只是读取我的 cookie 并使用 redux-tookit 设置数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 防止 url 在响应集 cookie 中编码 - nodejs - Prevent url encode in response set cookie - nodejs 如何设置nodejs服务器,通过检查URL为客户端提供正确的文件? - How do I set up a nodejs server that gives the client the correct file by checking the url? 重定向到 json 响应中的 URL - Redirect to URL in json response 如何更改URL Websocket NodeJ(服务器/客户端) - How to change URL Websocket NodeJs (server/client) React和NodeJS:如何从服务器向客户端发送数据? - React and NodeJS: How can i send data from server to client? 如何使重定向等待来自服务器的响应? - How can I make the redirect wait for the response from the server? PassportJS和ExpressJS条件URL重定向 - PassportJS and ExpressJS conditional URL redirect 如何使用websocket将json中的base64 url​​数据从javascript客户端发送到nodejs服务器? - How to send base64 url data using json from javascript client to nodejs server using websocket? 我正在尝试返回 JSON 以通过 passportjs 成功进行身份验证,但我收到“错误在将标头发送到客户端后无法设置标头”。 - I am trying to return JSON for successful authentication via passportjs but I'm getting "Error Cannot set headers after they are sent to the client." 如何从所有 url 重定向未登录用户? 护照 - How can i redirect no-logged user from all urls? PassportJs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM