【问题标题】:How to get cookies value from client service to server service in react js?如何在 React js 中从客户端服务获取 cookie 值到服务器服务?
【发布时间】:2021-11-07 05:40:28
【问题描述】:

如何在 react js 中从客户端服务获取 cookie 值到服务器服务? cookie 成功存储在客户端,但是当我从服务器端尝试控制台时,它显示未定义。

请帮帮我!!

index.js(服务器端):

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
const app = express();
import cookieParser from "cookie-parser";
import connection from "./database/db.js";
import Router from "./routes/route.js";
import auth from "./middleware/auth.js";

const corsOptions = {
    origin: true, //included origin as true
    credentials: true, //included credentials as true
};

app.use(cors(corsOptions));
app.use(cookieParser());

app.use(bodyParser.json({ extended: true }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/', Router);
app.use(express.json());

const PORT = 8000;
app.listen(PORT, () => {
    console.log(`server is running successfully at ${PORT}`);
})

connection();

Auth.js(身份验证中间件(服务器端)):

import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';

const auth = async (req, res, next) => {
    try {

        const token = req.cookies['jwt'];
        console.log("The token is", token) //it shows undefined
        const verifyuser = jwt.verify(token, "mynameismohitkumarfromnationalinstituteoftechnologyagartala");
        const user = await profile.findOne({ _id: verifyuser._id });
        
        console.log(verifyuser);
        console.log(user);
        next();
    } catch (error) {
        res.status(401).json(error);
    }
}

export default auth;

【问题讨论】:

    标签: javascript node.js reactjs express cookies


    【解决方案1】:

    如果 cookie 为 HttpOnly,请查看 cookie 选项,然后您无法从客户端读取 cookie。

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多