甚至在我发出Post请求或Put时,req.user都未定义。但是,当我发出get请求时,我可以获取登录用户req.user的值。
技术背景 Node js,Express服务器,Mongoose,express-session,Angular 7.1。
当我使用邮递员时,它可以按预期工作。如果有人能启发我做错事情,我会很高兴
这是针对角度版本7的。我尝试将凭据设置为true,它适用于获取请求,但不适用于发布请求
这是我的代码
客户网站 这是页面组件ts
import {PostService} from './post.service';
export class HomepageComponent implements OnInit {
constructor(private _post: PostService) {
this._post.GetPost()
.subscribe(data => this.allPost = data);
}
}
关于createPost组件ts
import { Component, OnInit } from '@angular/core';
import {PostService} from '../homepage/post.service';
export class CreatePostComponent implements OnInit {
title: string;
desc: string;
authorid: string;
constructor(private post: PostService){}
PostSubmit(){
this.post.PostCreate(this.title, this.desc, this.authorid)
.subscribe(
data=>{this.router.navigate(['/Post']);},
(err) => {console.log(err.status);});
}
}
这是post service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class PostService {
constructor(private http: HttpClient) { }
GetPost(){
return this.http.get<any[]>('http://127.0.0.1:4000/post',{
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
});
}
PostCreate(title:string, description:string, id:string){
return this.http.post('http://127.0.0.1:4000/post'{title,description,id,
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
});
}
}
在服务器端。据我所知,护照配置工作正常。如果需要,我很乐意稍后将其包括在内。 服务器端post.js文件
router.get('/post', (req, res)=>{
console.log(req.user);
Post.find({})
.populate('author')
.sort({created_At: "desc"})
.exec((err, allPost)=>{
if (err) {console.log(err);}
res.json(allPost);
});
});
router.post('/post', (req, res)=>{
console.log(req.user);
if (!req.body.title||!req.body.description) {
return res.status(405).json({message:'Post is Empty'})
}
var newPost = {
title: req.body.title,
description: req.sanitize(req.body.description),
author: req.body.id
};
Post.create(newPost, (err, post)=> {
if (err) {return res.status(501).json(err);}
return res.status(201).json({message:'Post Successful'});
});
});