首页 > 解决方案 > 如何从 Express API 获取 cookie 到 React?

问题描述

我正在开发登录系统。在前端,当我单击登录按钮时,会运行一个函数,该函数使用 axios 进行 API 调用。这是功能

export const startLogin = ({email, password}) => dispatch =>
    new Promise((resolve, reject) =>
        axios.post(`${USERS_API_BASE_URL}/login`, {
            email,
            password,
        }, {
            withCredentials: true,
        }).then(res => {
            const {token, user} = res.data
            dispatch(setAuth({token, user}))
            resolve(res.data.token)
        }).catch(error =>
            reject(error.response ? error.response.data.message : "Check Your Connection. Please try again later")
        ))

API 是否发送 Cookie? 是的。我已经在 Postman 中使用它并按预期工作。使用 Postman 登录时,我可以转到身份验证保护的路由。这是在后端触发的登录功能

const generateToken = (user, res) => {
    const token = jsonWebToken.sign(
        {id: user.id},
        process.env.JWT_SECRET_KEY,
        {
            expiresIn: process.env.JWT_EXPIRY
        }
    );
    res
        .status(200)
        .cookie("token", token, {
            httpOnly: true,
            expires: new Date(Date.now() + process.env.JWT_EXPIRY * 24 * 60 * 60 * 1000)
        })
        .json({
            status: "Success",
            token,
            user
        })
}

React 中的登录功能是否正常工作 是的,它工作正常。只有当我不使用{withCredentials: true}. 否则它给了我错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v1/users/login. (Reason: header ‘content-type’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response

你实施了 CORS 吗? 是的,这是代码

// Creating the express app
const app = express()

app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true
}))

app.use(cookieParser())

如果我更改 cookieParser 和 cors 的位置,它会给我同样的错误。另外,如果我没有在 cors() 中放置选项,我会得到同样的错误并且不会收到任何 cookie!

我认为问题出在 axios 请求上,但 stackoverflow 上的其他解决方案都没有奏效

标签: reactjsexpressauthenticationreact-reduxmern

解决方案


您是否在 React package.json 中设置了代理属性?如果没有尝试添加以下行:

"proxy": "http://localhost:8000"

推荐阅读