When the Express framework is used for login and registration, the session value will be invalid when cross-domain requests are made. As a result, the cached session value is always undefined.
Cause: In principle, session requires cookie support. In cross-domain requests, clients do not carry local cookies to send requests. As a result, sessions are not cached and a new session is generated after each request.
Solutions:
-
Asynchronous requests (Ajax/AXIOS) add xhrFields:{withCredentials:true} to indicate that cookies are allowed in cross-domain requests.
// Ajax global configuration $.ajaxsetup ({xhrFields:{withCredentials:true}}); / / axios global configuration axios. Defaults. WithCredentials = trueCopy the code
-
The response header on the server side needs to be set to access-Control-allow-credentials = true to enable certificate-carrying Access on the client side. When the access-Control-allow-credentials header is set to true, the access-Control-allow-origin header cannot be * and must be set to the address of the client.
var express = require('express'); var session = require('express-session'); var app = express(); App. all('*', function(req, res, next) {res.header(" access-Control-allow-origin ", "http://127.0.0.1:3005"); Header (" access-Control-allow-credentials ",'true'); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); next(); }); Use (cors({credentials: true, origin: "http://127.0.0.1:3005", methods: "PUT,POST,GET,DELETE,OPTIONS", }))Copy the code