我有一个快递服务器,它使用具有简单“本地”配置的通行证。
当我使用Postman作为POST传递登录凭据时,我会得到200和会话cookie。
当我使用我的React网站上的Fetch将相同的登录凭据传递到相同的路由时,响应中没有“ Set-Cookie”标头,并且显然没有cookie。
在服务器端,我在app.js中有这个
:app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(config.secretKey));
app.use(session({
name: 'session-id',
secret: config.secretKey,
saveUninitialized: false,
resave: false,
store: new FileStore(),
cookie: {
maxAge: config.cookieAge,
// HttpOnly: true,
secure: true
},
rolling: true
}));
app.use(passport.initialize());
app.use(passport.session());
我在所有路线上都在app.js中进行了预检:
const corsOptionsDelegate = (req, callBack) => {
var corsOptions;
if(whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = {
origin: true,
credentials: true
};
} else {
corsOptions = { origin: false };
}
callBack(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);
在前端,我在这里进行访存:
fetch("https://localhost:3443/users/login", {
method: 'POST',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify({"username": "casey", "password":"yourmom"}),
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
window.console && console.log(json);
}).catch((err) => {
window.console && console.log(err);
});
}
对于Postman,服务器响应标头为:
Connection →keep-alive
Content-Length →59
Content-Type →application/json; charset=utf-8
Date →Sun, 16 Sep 2018 16:46:19 GMT
ETag →W/"3b-D8ddoT95RFz3MPcsy1MlONKmP8w"
X-Powered-By →Express
set-cookie →session-id=s%3Ah7PRasfW-9Ch38U744Ga5Z57u-BD5tRG.lxwv0hrfLiRb3mim%2F7WV0Jl5U4lr7476zo0ZYBInZ0o; Path=/; Expires=Sun, 16 Sep 2018 17:46:19 GMT; HttpOnly; Secure
但是在获取服务器响应头之后:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Connection: keep-alive
Content-Length: 59
Content-Type: application/json; charset=utf-8
Date: Sun, 16 Sep 2018 17:32:45 GMT
ETag: W/"3b-D8ddoT95RFz3MPcsy1MlONKmP8w"
Vary: Origin
X-Powered-By: Express
我一直试图解决这一问题,但我真的不知道问题出在哪里。我不再收到控制台日志错误(一旦我对CORS进行了排序),并且响应很好,只是害羞了一个cookie。