NodeJS 如何在React中获取从Express js api(MERN堆栈)传递cookie

4si2a6ki  于 2022-11-04  发布在  Node.js
关注(0)|答案(2)|浏览(175)

我在express js中有一个api,它将token存储在客户端的cookie中(react)。只有当用户登录到站点时才会生成cookie。例如,当我用postman测试登录api时,cookie如预期的那样生成,如下所示:

但是当我用react.js登录时,浏览器中没有发现cookie。看起来cookie没有传递到前端,如下面的截图所示:

当我们收到一条警告消息时,这意味着express api工作正常,没有任何错误!!
下面是我在express js上的index.js文件,其中也包含cookie-parser中间件

require("dotenv").config();
const port = process.env.PORT || 5050;
const express = require("express");
const app = express();
const cors = require("cors");
const authRouter = require("./routes/auth");
var cookieParser = require('cookie-parser')

connect_db();

app.use(express.json());
app.use(cookieParser())
app.use(cors());
app.use("/" , authRouter);

app.listen(port , () => {
    console.log("Server is running!!");
})

用于设置仅来自express api的cookie的代码controller

const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt')

const login = async (req, res) => {
    const { email, password } = req.body;
    try {
        const checkDetails = await User.findOne({ email });
        if (checkDetails) {
            const { password: hashedPassword, token, username } = checkDetails;
            bcrypt.compare(password, hashedPassword, function (err, matched) {
                if (matched) {
                    res.cookie("token", token, { expires: new Date(Date.now() + (5 * 60000)) , httpOnly: true }).json({ "message": "You logged in sucessfully!" });
                } else {
                    res.status(500).json({ "message": "Wrong password" });
                }
            });
        } else {
            res.status(500).json({ "message": "Wrong email" });
        }
    } catch (error) {
        console.log(error.message);
    }
}

下面是react.js代码,我使用它在package.json文件中从api获取数据,而不使用代理

if (errors.length === 0) {

      const isLogin = await fetch("http://localhost:5000/api/login", {
        method: "POST",
        body: JSON.stringify({ email, password }),
        headers: {
          "Content-Type": "application/json"
        }
      });
      const res = await isLogin.json();
      if(res) alert(res.message);
    }

我想知道“在 Postman 中得到cookie而在浏览器中没有”背后的原因是什么。我需要使用任何react包吗?
网络选项卡屏幕截图可能会对您有所帮助。If I see in the network tab I get the same cookie, set among the other headers

sr4lhrrt

sr4lhrrt1#

据我所知,fetch不会发送带有浏览器为该域存储的cookie的请求,同样,它也不会存储在响应中接收到的任何cookie。这似乎是fetch的预期行为。
要覆盖此设置,请尝试在发出请求时设置凭据选项,如下所示:

fetch(url, {  
  // ...
  credentials: 'include'  
})

或者,可替换地:

fetch(url, {  
  // ...
  credentials: 'same-origin'  
})

您可以阅读更多有关这两种here之间差异的信息。

erhoui1w

erhoui1w2#

我通过代码中的两处更改解决了错误
在前端只添加了credentials: 'include'

fetch(url, {  
         method : "POST"
         body : body,
         headers : headers,
         credentials: 'include'  
      })

在后端,只需将app.use(cors());替换为

app.use(cors({ origin: 'http://localhost:3000', credentials: true, exposedHeaders: ['Set-Cookie', 'Date', 'ETag'] }))

这是它得到了解决,现在我有cookie存储在我的浏览器!!!太好了。感谢这篇文章:

https://www.anycodings.com/2022/01/react-app-express-server-set-cookie-not.html

相关问题