后端设置了Set-Cookie:
// 给客户端回复HTTP报文
void HttpServer::HandleResponse(const string &json, int sock,const string& sessionId,const string& url)
{
string httpResponse;
httpResponse += "HTTP/1.1 200 OK\r\n";
//cerr << "请求行构建完成" << endl;
//指定内容类型json
httpResponse += "Content-Type:application/json\r\n";
httpResponse += "Access-Control-Allow-Origin:*\r\n";
httpResponse += "Access-Control-Allow-Credentials:true\r\n";
httpResponse += "Access-Control-Allow-Headers:Set-Cookie\r\n";
//正文部分的长度/字节数
httpResponse += "Content-Length:";
int length = (int)json.size();
httpResponse += std::to_string(length);
httpResponse += "\r\n";
Json::Value root;
Json::Reader reader;
reader.parse(json,root);
cerr << url << endl;
cerr << sessionId.empty() << endl;
cerr << root["userId"] << endl;
if(sessionId.empty()&& url == "/login" && root["status"].asString()=="true")
{
string newSessionId = generateSessionId();
httpResponse += ("Set-Cookie:SessionId=" + newSessionId + "; Path=/; HttpOnly\r\n");
}
httpResponse += "\r\n";
httpResponse += json;
ssize_t s = send(sock,httpResponse.c_str(),httpResponse.size(),0);
cerr << httpResponse << endl;
}
打印出来的response报文也是有set-cookie的
但是前端vue这里怎么也接收不到
http.post("/login",this.loginForm)
.then(response=>
{
console.log(response)
if(response.data.status === "true")
{
// 从响应头中提取 sessionId
const sessionId = response.headers['Set-Cookie'].split(';')[0].split('=')[1];
console.log(sessionId)
localStorage.setItem('sessionId', sessionId);
this.$router.push("/personalCenter");
}
else{
alert("用户名或密码错误,请重试")
}
}
)
.catch(error=>{
alert("网络异常,请重试")
}
)
根本没有这个headers
我也允许第三方cookie了,跨域也允许了,httpOnly也删过了也没用,怎么办?求大佬解惑
......
不是所有的 HTTP Header 在前端代码中都可以访问到,Set-Cookie 就是一个前端代码无法访问的 HTTP Header
这些 Header 被浏览器提供给前端代码访问前已经被滤除。浏览器收到 Set-Cookie 响应头后会修改对应的 Cookie,你可以访问修改后的 cookie