简体   繁体   English

express.js 和 react.js cookie 保存到浏览器但不工作?

[英]express.js and react.js cookie saved to browser but not working?

I have a backend server using express.js I use react for my front end, so when I log in, the cookie will be saved in the browser but for some reason the session is not persisted and when I try to access some information from some route that requires authentication it will deny the access.我有一个使用 express.js 的后端服务器,我在前端使用 react,所以当我登录时,cookie 将保存在浏览器中,但由于某种原因,session 没有持久化,当我尝试从某些访问某些信息时需要身份验证的路由将拒绝访问。 I use postman to login and it will persist the session with no problem and can access routes that require authentication, so there must be a problem in the front end that it will not be created here's my codes:我使用 postman 登录,它会坚持 session 没有问题,并且可以访问需要身份验证的路由,所以前端肯定有问题,它不会创建这里是我的代码:

Backend:后端:

var cors = require('cors')

app.use(cors({
  origin: 'http://localhost:3000',
  methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'],
  credentials: true
}));

Front end:前端:

const postData = () => {  //this is for login
    const requestBody = {
      username: name,
      password: password,
    };
    const config = {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      withCredentials: true,
      accept: "application/json",
    };
    axios
      .post(`${myUrl}/login`, qs.stringify(requestBody), config)
      .then((res) => {
        console.log(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

const getData = async () => { //to access some data that requires authentication
    axios
      .get(`${myUrl}/edit`)
      .then((res) => {
        console.log(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

when I log in with my front end I get a success message that I put (successfully logged in) so that means there is no problem with the post request and the CORS there's only one problem which is the front-end, what might be the problem?当我使用前端登录时,我收到一条成功消息(成功登录),这意味着发布请求没有问题,CORS 只有一个问题是前端,可能是什么问题?

PS: what's so interesting is that the cookie is actually saved in the browser but when I try to access some information that requires authentication it denies access! PS:有趣的是cookie实际上保存在浏览器中,但是当我尝试访问一些需要身份验证的信息时,它拒绝访问! 在此处输入图像描述

try to put the credentials to true in the get request as well:尝试在获取请求中也将凭据设置为 true:

const getData = async () => { //to access some data that requires authentication
    axios
      .get(`${myUrl}/edit`, { withCredentials: true })
      .then((res) => {
        console.log(res.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM