[英]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.