我正在使用nodejs,express,cookie解析器和angular6。现在,angular在http://localhost:4200
中运行,node / express在http://localhost:3000
中运行。我还放了
const cors = require('cors');
app.use(cors());
在我的app.js
节点中,因此角度节点和节点都可以通信。
在我的登录路线中,我创建了一个带有令牌的纯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
。在控制台中,我看到token from validate : undefined
因此,我确定angular可以成功到达验证中间件,但是无法获取cookie。
我不明白为什么cookie不存在。是我的synatx吗?一开始没有设置吗?我应该在每个请求中都包含它吗? localhost
中的端口是否不同?我提供了尽可能多的细节,如果您需要更多,请告诉我。请帮助我进行调试,因为我迷路了。
谢谢