gpt4 book ai didi

reactjs - Set-Cookie 来自服务器的响应,但不存储在存储 cookie 中

转载 作者:行者123 更新时间:2023-12-03 14:38:33 25 4
gpt4 key购买 nike

我的 Graphql 服务器有问题并做出前端 react 。

提交“signin”突变时,会正确处理突变并接收数据。
“Set-Cookie”在响应 header 中接收,但未存储在浏览器 cookie 中。
我已经尝试过 Stack Overflow 上无数其他讨论中提出的解决方案,但无济于事。

enter image description here

enter image description here

这是我的后端代码:

index.js

    const express = require("express");
const mongoose = require("mongoose");
const { ApolloServer, AuthenticationError } = require("apollo-server-express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const jwt = require("jsonwebtoken");
const resolvers = require("./graphql/resolvers");
const typeDefs = require("./graphql/typeDefs");
require("dotenv").config();

const users = [
{
id: 1,
name: "Test user",
email: "your@email.com",
password: "$2b$10$ahs7h0hNH8ffAVg6PwgovO3AVzn1izNFHn.su9gcJnUWUzb2Rcb2W" // = ssseeeecrreeet
}
];

mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("DB Connected"))
.catch(err => console.error(err));

const corsOptions = {
credentials: true,
origin: "http://localhost:3000"
};
const app = express();
const port = 4000;
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const context = async request => {
let authToken = null;
let currentUser = null;
const { headers } = request.req;
try {
authToken = headers.authorization || "";
if (authToken) {
currentUser = jwt.verify(authToken, process.env.SECRET_KEY);
}
} catch (error) {
throw new AuthenticationError(
"Authentication token is invalid, please log in"
);
}
return { request, currentUser };
};

const server = new ApolloServer({
typeDefs,
resolvers,
context
});

server.applyMiddleware({ app, path: "/graphql" });

app.listen(port, () => console.log(`Server started: http://localhost:${port}`));

解析器.js

module.exports = {
Mutation: {
signin: async (root, args, ctx) => {
console.log(ctx.currentUser);
// Make email lowercase
const email = args.email.toLowerCase();
// Check if User exists
const userExist = await User.findOne({ email });
if (!userExist) {
throw new Error("User does not exist, please signup for new account");
}
// Check if passwords match
const match = await bcrypt.compare(args.password, userExist.password);
if (!match) {
throw new Error("Invalid username or Password");
}
// Create a token and assign
const token = jwt.sign(
{ email: userExist.email, id: userExist._id },
process.env.SECRET_KEY,
{ expiresIn: "1day" }
);
// Assign to cookie
ctx.request.res.cookie("token", token, {
httpOnly: true,
maxAge: 60 * 60 // 1 Hour
// secure: true, //on HTTPS
// domain: 'example.com', //set your domain
});
return userExist;
}
}
};

然后在客户端(React)端:

import React, { useContext, useReducer } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import App from "./App";
import Splash from "./pages/Splash";
import Context from "./context";
import reducer from "./reducer";
import ProtectedRoute from "./ProtectedRoute";

import * as serviceWorker from "./serviceWorker";

import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";

const client = new ApolloClient({
link: createHttpLink({
uri: "http://localhost:4000/graphql",
credentials: "include"
}),
cache: new InMemoryCache()
});

const Root = () => {
const initialState = useContext(Context);
const [state, dispatch] = useReducer(reducer, initialState);

return (
<Router>
<ApolloProvider client={client}>
<Context.Provider value={{ state, dispatch }}>
<Switch>
<ProtectedRoute exact path="/" component={App} />
<Route path="/login" component={Splash} />
</Switch>
</Context.Provider>
</ApolloProvider>
</Router>
);
};

ReactDOM.render(<Root />, document.getElementById("root"));

Login.js 组件

// Imports Omitted

export default function SignIn() {

const onSubmit = async ({ email, password }) => {
const variables = { email, password };
const client = new GraphQLClient(BASE_URL);
const data = await client.request(SIGNIN_MUTATION, variables);
console.log(data);
};


// return info omitted

最佳答案

在 resolver.js 中将 SameSite:None 更改为 SameSite:Lax

ctx.request.res.cookie("token", token, {
httpOnly: true,
maxAge: 60 * 60 // 1 Hour
// secure: true, //on HTTPS
// domain: 'example.com', //set your domain
sameSite: 'lax',
}
引用:
https://web.dev/samesite-cookies-explained/#explicitly-state-cookie-usage-with-the-samesite-attribute
https://github.com/GoogleChromeLabs/samesite-examples/blob/master/javascript-nodejs.md

关于reactjs - Set-Cookie 来自服务器的响应,但不存储在存储 cookie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567880/

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