Scenario: For example, there are two interfaces, user login interface a, and user information acquisition interface b. There is no problem at all when calling from the browser. Now when we need to use jq's
ajax
to call these two interfaces, something goes wrong.
Let’s talk about the browser first.
I entered the login interface a address in the browser, passed the parameters, and the login was successful. The server (php) stores my user ID, user name, etc. in session
. Next, request the user information interface b. The server directly finds the user information from the session and returns to the browser. Success!
Let’s talk about ajax.
I used ajax to call the login interface in js, returned success information, and the login was successful. User information is also stored in the session. But when I used ajax to call interface b to obtain user information, something went wrong, prompting session
not found.
I checked it in the console. After the browser successfully logs in, the information of set-cookie
will be returned in the response header. The next time you request the interface under the same domain name, cookie
will be automatically sent in the request header. To obtain the data of session
in the server.
In the case of an ajax request, successful login will also return set-cookie
information in the response header. However, the next time you request an interface under the same domain name, cookie
will not be automatically sent, so the server cannot be found. session
data.
Then the question is:
If I want to get the session data, do I need to manually send the cookie when making an ajax request? If not, how to get the session data?
Please ask God for answers!
ajax
请求添加参数xhrFields: { withCredentials: true },
php settings
header('Access-Control-Allow-Credentials:true');
Session relies on cookies. Where are the cookies on your server stored?
Even if you pass the cookie in your client's browser, is it consistent with the cookie in the server?
So session is not possible on the server. You can only use tokens, and you need to use redis or something to store information in the background.