无法在mern应用程序中将cookie设置到浏览器

问题描述 投票:0回答:1

当用户尝试登录时,我尝试设置两个令牌。其中之一是refresh_token,另一个是access_token。由于我在前端使用 redux,因此我的 access_token 将设置为 redux 状态,而我的刷新令牌应存储在浏览器 cookie 中。除了我的饼干之外,一切都工作正常。这是我的代码:

服务器.js:


require('dotenv').config()
const express = require('express')
const app = express()
const cors = require('cors')
const cookieParser = require('cookie-parser')
const corsOption = require('./config/corsOption')
const PORT = process.env.PORT || 3500
const authHandler = require('./routes/authRoutes')


app.use(cookieParser(process.env.COOKIE_SECRET))
app.use(
    cors({
        credentials: true,
        origin: "http://localhost:3000",
    }))
app.use(express.json())


app.use('/',authHandler)

app.get('/',(req,res)=>{
    res.status(200).json({ 'message': 'Server responding successfully.'})
})

app.all("*",(req,res) => {
    res.status(404).json({'message':'Not found!'})
})

app.listen(PORT , ()=>{
    console.log(`Server is running in port ${PORT}`)
})

登录控制器:

const jwt = require('jsonwebtoken')
const dbConnections = require('../config/dbConnect')
const bcrypt = require('bcrypt')



const loginUser = async(req,res) =>{
    try{
        const database = await dbConnections()
        const collection = database.collection('users')

        const { email , password } = req.body

        if(!email || !password){
            return res
            .status(400)
            .json({ "message": "Failed. No empty field allowed!" })
        }

        if(!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)){
            return res
            .status(404)
            .json({ "message": "Invalid email format!" })
        }
        const query = { email : email }
        const user = await collection.findOne(query)

        if(!user){
            return res
            .status(400)
            .json({
                "message":"No user found with this email. Please signup."
            })
        }

        const match = await bcrypt.compare(password,user.password)

        if(!match) {
            return res
            .status(400)
            .json({
                "message":"Invalid password!"
            })
        }

        const refresh_token = jwt.sign({ 
                email:email,
                role: user.role
            },
            process.env.REFRESH_TOKEN,
            {expiresIn: '2h'}
        )

        const access_token = jwt.sign({ 
                email:email,
                role: user.role
            },
            process.env.REFRESH_TOKEN,
            {expiresIn: '15m'}
        )


        res.cookie('refresh_token', refresh_token, {
            path: "/",
            sameSite: "none",
            httpOnly: true,
            secure: true,
        })

        res
        .status(200)
        .json({ 
            "access_token": access_token,
            "message": "Login successfully." 
        })

    }catch(err){
        console.log(err)
    }
}

前端:

store.js:

import { configureStore } from "@reduxjs/toolkit"
import authSlice from "../feature/auth/authSlice"
import { apiSlice } from "./api/apiSlice"

export const store = configureStore({
    reducer:{
        auth : authSlice,
        [apiSlice.reducerPath] : apiSlice.reducer,
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(apiSlice.middleware)
})

apislice.js:

import { createApi , fetchBaseQuery } from "@reduxjs/toolkit/query/react"


export const apiSlice = createApi({
    baseQuery: fetchBaseQuery({
        baseUrl: 'http://localhost:3500'
    }),
    credentials: 'include',
    tagTypes: [],
    endpoints: builder => ({})
}) 

authApiSlice.js

import { apiSlice } from "../../app/api/apiSlice";


export const authApiSlice = apiSlice.injectEndpoints({
    endpoints: builder =>({

        login: builder.mutation({
            query: ( credentials ) =>({
                url   : '/user/login',
                method: 'post',
                body  : credentials,
            })
        }),

    })
}) 

export const {
    useLoginMutation,
} = authApiSlice

authSlice.js

import { createSlice } from "@reduxjs/toolkit"

const initialState = {
    user : {},
}

export const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        logIn: (state,action) =>{
            state.user = action.payload
        },
        signUp: (credentials) =>{
            
        },
        logOut: () =>{

        }
    }
})


export const { logIn , logOut , signUp} = authSlice.actions
export default authSlice.reducer

我在本地尝试了不同的浏览器。但结果似乎都是一样的。 我已检查网络选项卡。我在那里找到了我的 cookie,但不在应用程序选项卡中。

reactjs express redux cookies jwt
1个回答
0
投票

我希望需要这样的 maxAge 属性

res.cookie('refresh_token',refresh_token,{ 小路: ”/”, 同一站点:“无”, httpOnly:正确, 安全:假, 最大年龄: 2 * 60 * 60 * 1000, // 2 小时 });

© www.soinside.com 2019 - 2024. All rights reserved.