[英]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.