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



我需要设置cookie与http仅在服务器使用护照js ("Google"),我设置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_solutionlocationservernode_modulesexpresslibresponse.js:794:10)
at ServerResponse.location (H:1HF_solutionlocationservernode_modulesexpresslibresponse.js:915:15)
at ServerResponse.redirect (H:1HF_solutionlocationservernode_modulesexpresslibresponse.js:953:18)

我只能设置cookie或重定向,但我需要两者。请帮忙这是我的代码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

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'] }));

在客户端i调用

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

我尝试使用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);
});

我也尝试end(),但我停留在服务器url。

附言我解决了这个问题。为了避免这种情况,我使用cookie,并设置我的userData和设置maxAge 5分钟,这不是秘密信息,在这5分钟后,他们将被清除,没有人读取这个数据,但如果有人可以,这不是一个问题。在客户端,我只是读取我的cookie和设置数据使用redux-tookit

相关内容

最新更新