NodeJS 如何发送Cookie

nvbavucw  于 2022-12-26  发布在  Node.js
关注(0)|答案(2)|浏览(196)

我正在尝试通过后端接口发送cookie,当我用 Postman 测试时,它是按要求完成的,问题是浏览器中没有发送cookie。
下面是我的代码:

    • 服务器. js**
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import  userRouter from "./routes/userRoutes.js";
import fileUpload from "express-fileupload";
dotenv.config();

const app = express();
app.use(bodyParser.json({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(fileUpload())
app.use(cors({ origin: true, credentials: true }));

//routes
app.use('/user' , userRouter)

const PORT = 5000;
mongoose.connect(process.env.MONGODB_URL , {useNewUrlParser : true , useUnifiedTopology : true})
    .then(() => app.listen(PORT , () => console.log(`Server is running on port : http://localhost:${PORT}`)))
    .catch((error) => console.log(error))

我通过登录功能发送Cookie:

export const login = async (req,res) => {
    try {
        const { email, password } = req.body;

        //check if empty
        if (!email) return res.status(400).json({ message: "Please write your Email." });
        if (!password) return res.status(400).json({ message: "Please write your Password" });

        //check email
        const user = await Users.findOne({ email });
        if (!user) return res.status(400).json({ message: "This email does not exist." });

        //check password
        const check_password = await bcrypt.compare(password, user.password);
        if (!check_password) return res.status(400).json({ message: "Password is incorrect." });

        const refresh_token = createRefreshToken({ id: user._id });
        const access_token = createAccessToken({ id: user._id });

        res.cookie('refreshtoken', refresh_token, {
            httpOnly:false,
            path: '/user/refresh_token',
            maxAge: 30*24*60*60*1000 // 30days
        });

        res.json({
            message: "Login success.",
            user,
            access_token
        });

    } catch (error) {
        return res.status(500).json({ message: error.message });
    }
}

在客户端我使用了redux:

export const login = (data) => async (dispatch) => {
    try {
        dispatch({ type: TYPES.NOTIFY, payload: { loading: true } });
        const res = await axios.post('http://localhost:5000/user/login',data);
        dispatch({
            type: TYPES.AUTH, payload: {
                token: res.data.access_token,
                user: res.data.user
            }
        });
        localStorage.setItem('token', res.data.access_token);
        dispatch({
            type: TYPES.NOTIFY,
            payload: {
                success: res.data.message
            }
        })

    } catch (error) {
        dispatch({
            type:TYPES.NOTIFY,
            payload:{
                error : error.response.data.message
            }
        })
    }
}
  • ------编辑----------
    我使用了axios.defaults.withCredentials,但问题仍然相同:
export const login = (data) => async (dispatch) => {
try {
    dispatch({ type: TYPES.NOTIFY, payload: { loading: true } });
    const res = await axios.post('http://localhost:5000/user/login',data , axios.defaults.withCredentials = true);
    dispatch({
        type: TYPES.AUTH, payload: {
            token: res.data.access_token,
            user: res.data.user
        }
    });
    localStorage.setItem('token', res.data.access_token);
    dispatch({
        type: TYPES.NOTIFY,
        payload: {
            success: res.data.message
        }
    })

} catch (error) {
    dispatch({
        type:TYPES.NOTIFY,
        payload:{
            error : error.response.data.message
        }
    })
}

};

ua4mk5z4

ua4mk5z41#

    • 溶液1**

我也遇到过这个问题。我删除了之前存储的所有cookie。这对我很有效。

    • 溶液2**

使用请求对象中的setHeader函数

const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");

app.use(express.json());

app.use(cookieParser());

app.get("/", (req, res) => {
  res.setHeader("Set-Cookie", "name=langesh");

  res.send("hello");
});

app.get("/get-cookie", (req, res) => {
  res.send(req.cookies);
});

app.listen(4000);
w3nuxt5m

w3nuxt5m2#

在axios中,您必须启用该选项

axios.defaults.withCredentials = true

您可以在此post中查看更多详细信息

相关问题