I have a controller made just to test cookies:
export const checkCookie = async (req: Request, res: Response) => {
res.status(200).json({ message: "Hello" });
};
and then router:
router.get("/login", checkCookie);
and in postman i get:
{
"message": "Hello"
}
i have app.ts
file:
import express, { Express } from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
//
import userRouter from "./routes/userRoutes";
import cardsRouter from "./routes/cardsRoutes";
import contactsRouter from "./routes/contactsRoutes";
import transferRouter from "./routes/transferRoutes";
import authRouter from "./routes/authRoutes";
//
const app: Express = express();
app.use(express.json());
app.use(cookieParser());
// app.use((req, res, next) => {
// console.log("hello from the middleware 2 ");
// next();
// });
app.get("/", (req, res) => {
res.cookie("name", "Test");
res.cookie("cookieName", "1", {
expires: new Date(Date.now() + 900000),
httpOnly: true,
});
});
app.get("/", (req, res) => {
res.send(req.cookies);
});
app.use(
cors({
credentials: true,
origin: "http://localhost:4200",
})
);
app.use("/api/v1", [
userRouter,
cardsRouter,
contactsRouter,
transferRouter,
authRouter,
]);
export default app;
I want to set a cookie after a call from the client:
url = 'http://localhost:8000/api/v1/login';
token: string = '';
async login(formObject: any) {
console.log('logging');
try {
const res = await axios.get(`${this.url}`, { withCredentials: true });
console.log(res.data);
console.log('http cookie set!');
} catch (error) {
console.error(error);
}
}
the console says:
logging
Object { message: "Hello" }
http cookie set!
But when i go to dev tools -> storage -> cookies
theres no cookie.
Why i cant set a cookie with Node.js? I have cookie-parser, and i dont have any idea why i dont have this cookie.
edit:
i tried adding:
res.send(req.cookies);
but it didnt help.