最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Chrome 开发工具应用程序选项卡中缺少 Cookie,但在网络部分下可见

网站源码admin41浏览0评论

Chrome 开发工具应用程序选项卡中缺少 Cookie,但在网络部分下可见

Chrome 开发工具应用程序选项卡中缺少 Cookie,但在网络部分下可见

我正在尝试使用 React(前端)和 Node+Express 作为后端在按钮点击时设置一个 cookie。我可以在网络选项卡下的响应标头中看到 cookie,但应用程序选项卡下未设置相同的 cookie。我尝试了另一篇文章中提到的所有内容,但无法找到解决方案。

服务器端 index.js:

const expreess=require('express')
const cors=require('cors')
const { default: mongoose } = require('mongoose')
const app =expreess()
const user_routes=require("./routes/user_routes")
const login_routes=require("./routes/login_routes")
const feedback_routes=require("./routes/feedback_routes")
const cookieParser=require('cookie-parser')
const {requireAuth} =require("./middleware/middleware")

app.use(cookieParser())
app.use(cors({ origin: 'http://localhost:5173', credentials: true, exposedHeaders: ['Set-Cookie', 'Date', 'ETag'] }))
app.use(expreess.json())
app.use(function(req, res, next) {
    res.header('Content-Type', 'application/json;charset=UTF-8')
    res.header('Access-Control-Allow-Credentials', true)
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    )
    next()
  })
app.use("/users",user_routes)
app.use("/login",login_routes)
app.use("/feedback",feedback_routes)


mongoose.connect("mongodb+srv://testuser:[email protected]/feedback-data")
    .then(()=>{app.listen(5000,()=>console.log("MongoDB connection Successfull & Server started on port 5000...."))})
    .catch((error)=>console.log("Server start failed ",error))
<script src=".6.3/umd/react.production.min.js"></script>
<script src=".6.3/umd/react-dom.production.min.js"></script>
回答如下:

我在使用 React(vite) 时遇到了同样的问题。不要使用

http://127.0.0.1:5173/
访问您的前端。而是使用
http://localhost:5173/
访问它。即使两者相同,网页也是从 http://localhost:5173/ 加载的,并且它向 http://127.0.0.1:5173/ 发出 GET 请求。所以这是一个跨域请求 默认情况下,浏览器不会发送凭据(例如 Cookie 和 HTTP 身份验证)。

有关上一个问题的更多信息:Can't get the cookie data from Go server with React

发布评论

评论列表(0)

  1. 暂无评论