Node.js 无法在具有节点和节点的中间件中获取cookie
我正在使用nodejs、express、cookie解析器和angular 6。现在,angular在Node.js 无法在具有节点和节点的中间件中获取cookie,node.js,angular,cookies,login,Node.js,Angular,Cookies,Login,我正在使用nodejs、express、cookie解析器和angular 6。现在,angular在http://localhost:4200和节点/快进http://localhost:3000。我还把 const cors = require('cors'); app.use(cors()); 在我的app.js节点中,angular和node都可以通信 在我的登录路径中,我使用令牌创建了一个仅http的cookie,然后我发送回一个带有一些信息和用户id的JSON res.cookie
http://localhost:4200
和节点/快进http://localhost:3000
。我还把
const cors = require('cors');
app.use(cors());
在我的app.js
节点中,angular和node都可以通信
在我的登录路径中,我使用令牌创建了一个仅http的cookie,然后我发送回一个带有一些信息和用户id的JSON
res.cookie("SESSIONID", token, {httpOnly:true, secure:true});
res.json({ success:true, msg:'you are logged in', userid: resolved.id});
我假设SESSIONID cookie随每个请求一起发送回服务器,因此我不必在每个请求之前自己设置它
在我的中间件中,我希望从cookie中获取令牌以检查它。所以,我喜欢
const token = req.cookies.SESSIONID;
console.log('token from validate : ', token);
//check token and expiration, either next(); or redirect back
在我的路线上,我有
router.get('cms/account', myMiddleware.required(), (req, res)=>{
res.json({ msg:'profile data'});
});
我的配置文件服务联系节点的帐户路由
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class ProfileService {
constructor(private http:Http) { }
getProfile(){
return this.http.get('http://localhost:3000/cms/account').pipe(map(res => res.json()));
}
}
我的配置文件服务应该提供一些配置文件数据
import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../../services/profile.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
constructor( private profileService: ProfileService) { }
ngOnInit() {
this.profileService.getProfile().subscribe((data) =>{
console.log('profileService -- ', data);
})
}
}
登录后,我进入http://localhost:4200/cms/profile
。在控制台中,我看到来自validate:undefined的标记
因此,我确信angular成功地到达了验证中间件,但无法获得cookie
我不明白为什么饼干不在那里。是我的synatx吗?不是一开始就设定的吗?我应该在每个请求中都包含它吗?是本地主机中的不同端口吗?我尽可能多地提供了细节,如果你需要额外的信息,请告诉我。请帮我调试这个,因为我迷路了
谢谢检查浏览器开发人员工具中的“存储”选项卡,确保cookie实际设置了正确的令牌值。@Vivek我看到一个connect.sid
cookie,我假设它与我的不同。哦,等等。我一定忘了在节点中包含一些cookie包。cookie解析器可以创建cookie吗?或者我应该创建一个只有http的cookie,然后使用cookie解析器进行解析吗?感谢确保创建cookie的代码行正在执行res.cookie(“SESSIONID”,令牌,{httpOnly:true,secure:true});res.json({success:true,msg:'youarelogen',userid:resolved.id})
在这些行之前记录token
的值并检查。是的,在我执行res.cookie(“SESSIONID”,token,{httpOnly:true,secure:true})之前,token看起来正常代码>。此外,我还获取了用户ID
,将其放入localStorage,然后在浏览器开发人员工具中看到它我的localStorage。嘿,cookie不应该出现在浏览器开发工具中,因为它只是http,对吗?