简体   繁体   English

Session在Flask中没有存储在post请求中而是存储在get请求中

[英]Session is not stored in post request but stored in get request in Flask

I'm making front end in React.js and server on python flask and using mongodb as database.我在 React.js 中制作前端,在 python flask 上制作服务器,并使用 mongodb 作为数据库。 When I enter credentials on react js for logging in, I send data to server using axios. python checks the credentials, stores the user data on database and creates a user.当我在 react js 上输入凭据进行登录时,我使用 axios 将数据发送到服务器。python 检查凭据,将用户数据存储在数据库中并创建一个用户。 I create a session on python server using post request.我使用 post 请求在 python 服务器上创建了一个 session。 The problem is this that when I send the data to server using post request, it doesn't make a session even though i wrote the code for that.问题是,当我使用 post 请求将数据发送到服务器时,即使我为此编写了代码,它也不会生成 session。 This is the backend code.这是后端代码。

@app.route('/login', methods=['POST', "GET"])
def LoginScreen():
    if request.method == "POST":
        data = request.json
        email = data['email']
        password = data['password']
        user = db.Users.find_one({"email": email, "password": password})
        print(user['_id'])
        if user is None:
            return {"status": "fail"}
        else:
            session['user'] = {"userID": str(user['_id'])}
            print(session['user'])
            return {"status": "success"}
    else:
        session['user'] = "AbdulMunim"
        return 'LoginPage'

and this is the front end code这是前端代码

await axios
  .post("http://localhost:5000/login", {
    email: email,
    password: password,
  })
  .then((res) => {
    console.log("RES", res);
    if (res.data.status === "success") {
      navigate("/");
    } else {
      alert("Invalid Credentials");
    }
  });

When I use POST method to send data from react to flask, it doesn't stores the session but when use the localhost of server side and use login method which is GET, it stores the session.当我使用 POST 方法将数据从 React 发送到 flask 时,它不会存储 session,但是当使用服务器端的本地主机并使用 GET 登录方法时,它会存储 session。

Open chrome's developer tool to check if there's a set-cookie header in flask's response.打开chrome的开发者工具查看flask的响应中是否有set-cookie header。

If flask works fine, then the problem may happen on the frontend side.如果 flask 工作正常,那么问题可能发生在前端。

Try this:尝试这个:

axios.post('your_url', data, {withCredentials: true})

This may help you too: Does Axios support Set-Cookie?这也可能对您有帮助: Does Axios support Set-Cookie? Is it possible to authenticate through Axios HTTP request? 是否可以通过 Axios HTTP 请求进行身份验证?

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

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