问题发送cookie“ connect.sid”使用浏览器

发布于 2025-02-04 09:53:46 字数 2767 浏览 2 评论 0原文

我有一个与React(Front)创建的电子商务,同时用Express制作了背面。我的会话由护照JS处理,问题是我在没有任何问题的情况下建立了登录或寄存器,但是当我必须重新检查会话时,浏览器(Chrome)永远不会发送cookie,因此服务器是无法识别会话。我与Postman进行了检查,效果很好。有人知道为什么前部不发送cookie(“ connect.sid”)???

我将组件的代码留在React和路由器的代码中。

import { useContext, useEffect } from "react"
import ItemList from "./ItemList"
import { myContext } from "../contexto/contexto"
import { useHistory } from "react-router"

const ItemListContainer = () => {
  const contexto = useContext(myContext)
  const history = useHistory()
  const obj = {
    email: sessionStorage.getItem("user")
  }

  useEffect(() => {
    fetch(`http://localhost:8080/api/usuarios/check-session`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(obj)
    })
    .then(res => res.json())
    .then(json => {
      console.log(json)
      //if (json.session == false) history.push("/")
    })
    .catch(err => console.log(err))
  },[obj])

  return (
    <ItemList items={contexto.productos} />
  )
}

export default ItemListContainer

这是我的服务器:

const { Router } = require("express")
const router = Router()
const upload = require("../../utils/middlewares/multer")
let UsuariosController = require("./controller/usuariosController")
const textUsuarioYaRegistrado = "Email ya registrado!"
const textUsuarioInexistente = "Datos incorrectos!"
    
module.exports = (app,passport) => {
  app.use("/api/usuarios", router)
    
  let isLogin = (req, res, next) => {
    try {
      if (req.isAuthenticated()) {
        next()
      } else {
        res.json({session: false})
      }
    } catch (error) {
      console.log(error)
    }
  }
    
  let isNotLogin = (req, res, next) => {
    try {
      if (!req.isAuthenticated()) {
        next()
      } else {
        res.redirect(`${config.FRONT_URI}/productos`)
      }
    } catch (error) {
      console.log(error)
    }
  }
        
  //router.post("/nuevo", UsuariosController.createUsuario)
    
  router.post("/guardar-foto", upload.single("foto"), UsuariosController.guardarFoto)
    
  //router.post("/", UsuariosController.getUsuario)
    
  router.post("/nuevo",  passport.authenticate('register', {failureRedirect:`/api/usuarios/error/${textUsuarioYaRegistrado}`}), (req,res,next) => {
    res.json(req.body)
  });
    
  router.post("/", passport.authenticate('login', {failureRedirect:`/api/usuarios/error/${textUsuarioInexistente}`}), (req,res,next) => {       
    res.json(req.user)
  });

  router.get("/error/:errorMessage", (req,res,next) => {
    res.render("error", {error: req.params.errorMessage})
  })
    
  router.post("/check-session", isLogin, UsuariosController.getByEmail)

I have an ecommerce created with react (front), meanwhile the back is made with express. My session is handled by passport js, and the problem is that I establish the login or the register without any problem, but when I have to re-check the session, the browser (Chrome) never sends back the cookie, so the server is not able to recognize the session. I checked with postman and it works fine. Does someone know why the front does not send the cookie ("connect.sid")???

I leave here the code of the component in react and the code of my router.

import { useContext, useEffect } from "react"
import ItemList from "./ItemList"
import { myContext } from "../contexto/contexto"
import { useHistory } from "react-router"

const ItemListContainer = () => {
  const contexto = useContext(myContext)
  const history = useHistory()
  const obj = {
    email: sessionStorage.getItem("user")
  }

  useEffect(() => {
    fetch(`http://localhost:8080/api/usuarios/check-session`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(obj)
    })
    .then(res => res.json())
    .then(json => {
      console.log(json)
      //if (json.session == false) history.push("/")
    })
    .catch(err => console.log(err))
  },[obj])

  return (
    <ItemList items={contexto.productos} />
  )
}

export default ItemListContainer

Here is my server:

const { Router } = require("express")
const router = Router()
const upload = require("../../utils/middlewares/multer")
let UsuariosController = require("./controller/usuariosController")
const textUsuarioYaRegistrado = "Email ya registrado!"
const textUsuarioInexistente = "Datos incorrectos!"
    
module.exports = (app,passport) => {
  app.use("/api/usuarios", router)
    
  let isLogin = (req, res, next) => {
    try {
      if (req.isAuthenticated()) {
        next()
      } else {
        res.json({session: false})
      }
    } catch (error) {
      console.log(error)
    }
  }
    
  let isNotLogin = (req, res, next) => {
    try {
      if (!req.isAuthenticated()) {
        next()
      } else {
        res.redirect(`${config.FRONT_URI}/productos`)
      }
    } catch (error) {
      console.log(error)
    }
  }
        
  //router.post("/nuevo", UsuariosController.createUsuario)
    
  router.post("/guardar-foto", upload.single("foto"), UsuariosController.guardarFoto)
    
  //router.post("/", UsuariosController.getUsuario)
    
  router.post("/nuevo",  passport.authenticate('register', {failureRedirect:`/api/usuarios/error/${textUsuarioYaRegistrado}`}), (req,res,next) => {
    res.json(req.body)
  });
    
  router.post("/", passport.authenticate('login', {failureRedirect:`/api/usuarios/error/${textUsuarioInexistente}`}), (req,res,next) => {       
    res.json(req.user)
  });

  router.get("/error/:errorMessage", (req,res,next) => {
    res.render("error", {error: req.params.errorMessage})
  })
    
  router.post("/check-session", isLogin, UsuariosController.getByEmail)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文