gpt4 book ai didi

reactjs - 如何设置等同于 fetch 的 { credentials : "include" } in Redux Toolkit's createApi?

转载 作者:行者123 更新时间:2023-12-01 23:13:12 25 4
gpt4 key购买 nike

我有一个 express-react-typescript-redux-passport 项目,我在其中使用 redux 工具包中的 createApi 在我的后端调用 /getuser api。

我正在使用 passport-google-oauth20 策略对用户进行身份验证,并且用户已成功通过身份验证。

我的问题是没有调用passport js deserializeUser()函数(即使调用了serializeUser(),并且使用google策略对用户进行了身份验证),所以前端向后端发送请求时不会自动设置req.user参数.

怀疑没有调用 deserializeUser,因为我没有在我的 { withCredentials: true } 端点中设置 axio 的 {credentials: "include"}(或 fetch 的 createApi)参数。如何在RTK的createApi中发送这个参数?

如何指定凭据:包括在此处?

这是我的 createApi 函数

export const userApiSlice = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:4000",
prepareHeaders(headers) {
return headers;
},
}),
endpoints(builder) {
// debugger;
return {
fetchUser: builder.query<IUser, number | void>({
query: () => {
debugger;
return `/getuser`;
},
}),
};
},
});

这是我的服务器 index.js

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import session from "express-session";
import passport from "passport";

var GoogleStrategy = require("passport-google-oauth20").Strategy;
import { IGoogleAuthUser } from "./types/authTypes";
const PORT = process.env.PORT || 4000;

require("dotenv").config();

const app = express();

mongoose.connect(process.env.LOCAL_DB_ADDRESS, () => {
console.log("connected to mongoose db");
});

app.use(express.json());
app.use(cors({ origin: "http://localhost:3000", credentials: true }));

app.use(
session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user: IGoogleAuthUser, done: any) => {
//send a cookie to browser to store user id in session
const { id} = user;
console.log("serializeUser called");
return done(null, id);
});

// why isn't this called???
passport.deserializeUser((userId: string, done: any) => {
//attaches the cookie id from session to req.user
console.log("deserializeUser userId : ", userId);
return done(null, userId);
});

//google strategy
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback",
},
function (accessToken: any, refreshToken: any, profile: any, done: any) {
//this is called on succesful authentication with the above Google Stratety
console.log("successful authorization");
done(null, profile);
}
)
);

//when user clicks on 'login with google' /auth/google is hit
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile", "email"] }),
(req, res) => {
console.log("/auth/google called"); //this console.log does not get called, not sure why
}
);

app.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "http://localhost:3000/profile",
failureRedirect: "http://localhost:3000/login",
}),
function (req, res) {
// console.dir(req);
// Successful authentication, redirect home.
console.log("redirect to profile"); //this does get called
res.redirect("http://localhost:3000/profile");
}
);

app.get("/", (req, res) => {
res.send("Hello world.");
});

app.get("/getuser", (req: any, res: any) => {
//req should have user thanks to serializer/deserializer
console.log(req.user); // => returns undefined even after successful authentication
res.send(req.user);
});

app.listen(PORT, () => {
console.log(`Server Started on ${PORT}`);
});

为什么 deserializeUser() 没有被调用??

最佳答案

fetchBaseQuery 只是一个带有一些额外选项的 fetch 包装器。

可以这样

  baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:4000",
prepareHeaders(headers) {
return headers;
},
credentials: "include"
}),

        query: () => {
return { url: `/getuser`, credentials: "include" };
},

关于reactjs - 如何设置等同于 fetch 的 { credentials : "include" } in Redux Toolkit's createApi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69430093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com