DEV Community

廖珞君
廖珞君

Posted on

<Issue>React unable to successfully transfer cookies with backend

The following is my backend program:
corsconfig:
app.use(cors({
origin:'http://localhost:5173',
credentials : true,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT',"OPTIONS"],
allowedHeaders: ['Content-Type', 'Authorization'],

}));
cookie result
result.cookie('test', "123", {
httpOnly: false,
secure: false,
sameSite: "None",
expires: new Date(Date.now() + 3600000),
maxAge: 3600000,
});
result.status(201).send({
success: true,
message: "login successful"
});

The following is my frontend React program
fetch('http://192.168.0.172/login', {
method: 'POST',
credentials: 'include', // 包含 cookie
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'test', password: '123' })
})

When I initiate a request, the backend returns a success, and the cookie can be seen on the frontend web page, but the cookie is not obtained using cookies.get.
Why can I successfully obtain the cookie headers when I use fetch without react?
Are the cookies returned by the backend blocked? How can I successfully retrieve the cookies from the backend when using react?

Top comments (0)