javascript 无法从cookie获取jwt标记

rslzwgfq  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(146)

我用mern stack做了一个网站。我用jwt试着把它们存储在cookie里。我用参数调用了res.cookie函数(你可以在下面找到代码)。但是不知怎么的我在浏览器里找不到cookie。no cookie found(top portion) whereas name of cookie(=jwt) found in network tab in inspect. Please look at this screenshot
但是当我在inspect中检查网络选项卡时,Set-cookie中出现了一个cookie。
假设cookie已经存储,我尝试访问JWT令牌,但没有成功。
我提供下面的代码。
这是我的文件所有的路线都写在里面。

const express = require ("express")
const Resident = require("../models/residentModels");
const bcrypt = require("bcrypt");
// const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

const router = express.Router();

router.post("/register", async (req, res) =\> {
try {
const resident = new Resident(req.body);

        console.log(req.body);
    
        // password hash 
        // middleware
        const token = await resident.generateAuthToken();
    
        console.log("token: " + token);
    
        res.cookie("jwt", token, {
            httpOnly: true,
            expires: new Date (Date.now() + 12342)
        })
        // console.log(cookie);
    
        const newResident = await resident.save();
    
        console.log("hehe" + newResident);
        // console.log(newResident._id);
        // console.log(newResident._id.toString());
    
        res.status(200).send("Record Added Successfully");
    } catch (error) {
        console.log(error);
        res.status(200).send("Record Creation Unsuccessfull");
    }

})

router.post("/login", async (req, res) =\> {
try {
let blockNumber = req.body.blockNumber;
let flatNumber = req.body.flatNumber;
let password = req.body.password;

        console.log(blockNumber)
        console.log(flatNumber)
        console.log(password)
    
        const response = await Resident.findOne({blockNumber: blockNumber, flatNumber:flatNumber});
    
        console.log(response);
    
        const isMatch = await bcrypt.compare(password, response.password);
    
        console.log("isMatch: " + isMatch);
    
        const token = await response.generateAuthToken();
        console.log("token part: " + token);
    
        let cookie = res.cookie("jwt", token, {
            httpOnly: true,
            expires: new Date (Date.now() + 10000)
        })
        // console.log(cookie)
    
        // console.log(`this is the cookie awesome !! + ${req.cookies.jwt}`);
        let jwtToken = req.cookies;
        console.log("req.cookies.jwt: " + jwtToken);
    
        if(isMatch){
            res.status(200).send("Successful Login");
        }
        else{
            res.status(200).send("Invalid Login Details");
        }
    } catch (error) {
        res.status(200).send("Invalid Login Details");
    }

});

module.exports = router;

这是我的index.js文件:

const express = require("express");
require('./db/conn');
const Resident = require("./routes/residentRoutes");
var cors = require("cors");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

const app = express();

app.use(cors());
app.use(express.json());
app.use(Resident);
app.use(cookieParser());

const port = process.env.PORT || 8000;

const bcrypt = require("bcrypt");

const securePassword = async (password) =\> {
const passwordHash = await bcrypt.hash(password, 10);
console.log(passwordHash);

    const passwordMatch = await bcrypt.compare(password, passwordHash)
    console.log(passwordMatch);

}

securePassword("thapa@123");

const createToken = async () =\> {
const token = await jwt.sign({\_id: "63e677a57d45b06c8557441a"}, "thisisnotformyresumebutmyideology!!!",{
expiresIn: "20 seconds"
})
console.log(token);

    const userVerify = await jwt.verify(token, "thisisnotformyresumebutmyideology!!!");
    console.log(userVerify); // returns an object

}

createToken();

app.listen(port, () =\> {
console.log(`connection successful at port ${port}`);
})

在写入所有路由的文件中,变量jwtToken返回"undefined",结果很明显cookie没有被存储。
所以现在的问题是我如何存储cookie,我哪里做错了?
P.S.:我在前端使用React.js。
我的Login. jsx文件如下所示:

import axios from 'axios';
import React from 'react'
import { NavLink, useNavigate } from 'react-router-dom'

const Login = () => {

  let navigate = useNavigate();

  const loginButton = async (event) => {
    event.preventDefault();

    // console.log(event.target[0].value); // block number

    let blockNumber = event.target[0].value;
    let flatNumber = event.target[1].value;
    let password = event.target[2].value;

    const response = await axios.post('http://localhost:8000/login', {
      blockNumber: blockNumber,
      flatNumber: flatNumber,
      password: password
    })

    // console.log("response :" + response.data);
    console.log(response);

    if(response.status === 200){
      navigate("/dashboard");
    }
    else{
      alert("Invalid Login Details");
    }
  }

  return (
    <>
      <h1> Login </h1>
      <form onSubmit={loginButton}>
        <input type="number" placeholder='Block Number *' />
        <input type="number" placeholder='Flat Number *' />
        <input type="password" placeholder='Password *' />

        <button type="submit">Login</button>
        <NavLink to='/register'>or Click to Register</NavLink>
      </form>
    </>
  )
}

export default Login
0ejtzxu1

0ejtzxu11#

在index.js文件中
从以下位置交换这两个:

app.use(Resident);
app.use(cookieParser());

致:

app.use(cookieParser());
app.use(Resident);

在访问路由之前,您需要首先解析请求
序列决定了你如何放置你的代码

lmyy7pcs

lmyy7pcs2#

在浏览器开发者工具的应用标签中你能看到cookies吗?如果可以,你用的是axios吗?如果是,可能是因为这个原因,你需要添加withCredentials:在axios构造函数中为true。

axios("http://someurl", {
  method: "post",
  data: someJsonData,
  withCredentials: true
})

相关问题