[英]how to get cookie in react passed from express js api (MERN stack)
我在 express js 中有一个 api,它将令牌存储在客户端的 cookie 中(反应)。 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!!");
})
用于设置 cookie 的代码来自 express api 只有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);
}
}
这是我用来从 api 获取数据而不使用 package.json 文件中的代理的package.json
代码
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 而不是在浏览器中”背后的原因是什么。 我需要使用任何反应 package 吗?
.network 选项卡屏幕截图可能对您有所帮助。 If I see in the.network tab I get the same cookie, set among the other headers
据我了解, fetch
不会使用您的浏览器为该域存储的 cookie 发送请求,同样,它不会存储在响应中收到的任何 cookie。 这似乎是 fetch 的预期行为。
要覆盖它,请在发出请求时尝试设置凭据选项,如下所示:
fetch(url, {
// ...
credentials: 'include'
})
或者,或者:
fetch(url, {
// ...
credentials: 'same-origin'
})
您可以在此处阅读有关两者之间差异的更多信息。
我通过代码中的两个更改解决了我的错误
在前端刚刚添加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'] }))
就这样解决了,现在我的浏览器中存储了cookies!!! 伟大的。 感谢这篇文章:
https://www.anycodings.com/2022/01/react-app-express-server-set-cookie-not.html
在开发过程中我也遇到了同样的事情,让我来帮助你解决它,
首先,你在你的反应中使用代理 package.json,在私人下面: -
"private": true,
"proxy":"http://127.0.0.1:5000",
提及您的节点服务器正在运行的相同端口,例如:-
app.listen(5000,'127.0.0.1',()=>{
console.log('Server is Running');
});
以上两者必须相同,现在反应将像往常一样在端口 3000 上运行,但现在我们将创建代理来反应因此,反应和节点端口在代理的帮助下间接连接到相同的端口。
现在,当您从 React 发出 GET 或 POST 请求时,请不要提供完整的 URL,只提供您希望在后端获得响应并获得响应的路径,
示例:- 对发送请求做出反应,如下所示:-
const submitHandler=()=>{
axios.post('/api/loginuser',
{mobile:inputField.mobile,password:inputField.password})
.then((res)=>{
console.log(res);
})
.catch((err)=>{
console.log(err);
})
}
Node side where it will hit:-
app.post('/api/loginuser', async(req,res)=>{
//Your Code Stuff Here
res.send()
}
双方都应该点击相同的链接,这非常重要
它将 100%。 别忘了提
在服务器正在侦听的节点 main 上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.