'Reactjs client does not get cookie from Express server
My set up as below:
- Reactjs client in
http://localhost:3000 - Express server in
http://localhost:5000
Client:
import { useState } from "react";
import axios from "axios";
import "./App.css";
const API = axios.create({ baseURL: "http://localhost:5000" });
function App() {
const [auth, setAuth] = useState(false);
const login = () => API.post("/login").then((res) => setAuth(true));
const ping = () =>
API.post("/ping", { withCredentials: true }).then((res) =>
console.log(res)
);
return (
<div className="wrapper">
<button className="log-btn btn" onClick={login}>
Login
</button>
{auth && (
<button className="ping-btn btn" onClick={ping}>
Ping
</button>
)}
</div>
);
}
export default App;
Server:
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import jwt from "jsonwebtoken";
// express
const app = express();
// middlewares
app.use(express.json({ limit: "60mb" }));
app.use(cors());
app.use(cookieParser());
app.use(function (req, res, next) {
console.log("VLL");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header(
"Access-Control-Allow-Headers",
"X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept"
);
next();
});
// routes
app.post("/login", (req, res) => {
const token = jwt.sign({ name: "TOKEN" }, "SECRET_KEY", {
expiresIn: "24h",
});
res.cookie("token", token, {
httpOnly: true,
secure: false,
});
res.status(202).send("LOGGED IN");
});
app.post("/ping", (req, res) => {
console.log(req.cookies);
res.status("202").send("YOU GOT IT");
});
// run
app.listen(5000, () => {
console.log("Server is running on http://localhost:5000");
});
My scenario is
- Client click Login button to make a post request to api
/login - Server receive the request, make a jwt and put in httpOnly cookie then response to client
- Client click Ping button to make a post request (contains above cookie) to api
/ping - Server receive and verify jwt inside cookie from request
I can see the cookie sent back from server at step 2 (using Chrome Dev Tools):
token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiVE9LRU4iLCJpYXQiOjE2NDg1NDM0MTgsImV4cCI6MTY0ODYyOTgxOH0._PiVonFtdyCo3O-1Xwupd2zxlE-J8DWa9OONVeP4e_s; Path=/; HttpOnly
But I don't see it in the request at step 3 then in step 4 I get [Object: null prototype] {} when try to print req.cookies
How I can fix this problem ?
Thank you!
Solution 1:[1]
For someone who facing this problem like me. All lines have // NEW comment resolve this problem
Client:
import { useState } from "react";
import axios from "axios";
import "./App.css";
axios.defaults.withCredentials = true; // NEW
const API = axios.create({ baseURL: "http://localhost:5000" });
function App() {
const [auth, setAuth] = useState(false);
const login = () => API.post("/login").then((res) => setAuth(true));
const ping = () =>
API.post("/ping", { withCredentials: true }).then((res) =>
console.log(res)
);
return (
<div className="wrapper">
<button className="log-btn btn" onClick={login}>
Login
</button>
{auth && (
<button className="ping-btn btn" onClick={ping}>
Ping
</button>
)}
</div>
);
}
export default App;
Server:
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import jwt from "jsonwebtoken";
// express
const app = express();
// middlewares
app.use(express.json({ limit: "60mb" }));
app.use(
cors({
origin: "http://localhost:3000", // NEW
credentials: true, // NEW
})
);
app.use(cookieParser());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header(
"Access-Control-Allow-Headers",
"X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept"
);
next();
});
// routes
app.post("/login", (req, res) => {
const token = jwt.sign({ name: "TOKEN" }, "SECRET_KEY", {
expiresIn: "24h",
});
res.cookie("token", token, {
httpOnly: true,
secure: false,
});
res.status(202).send("LOGGED IN");
});
app.post("/ping", (req, res) => {
console.log(req.cookies);
res.status("202").send("YOU GOT IT");
});
// run
app.listen(5000, () => {
console.log("Server is running on http://localhost:5000");
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
