簡體   English   中英

無法獲取具有均值堆棧的req.body的數據

[英]Can't get data for req.body with mean stack

嘿,使用req.body時似乎看不到任何結果。 嘗試將數據從mongodbdatabase轉換為json格式,這是我的代碼:

我的服務器文件:

app.get('/api/category/posts', (req, res) => {
    Post.find({ categoryId: req.body._id }, function(err, posts) {
        res.json(posts);
    });
});

服務文件:

getPosts(_id): Observable<Post[]>{
            return this.http.get<Post[]>(this.apiUrl +"/category/posts");
              }

component.ts

this.appService.getPosts(_id)
    .subscribe(data =>this.posts=data);

您的api方法是get方法,並且您需要_id在req.body中。 這是錯誤的。
您需要更改獲取請求以同時發布在服務器文件和服務文件中的請求,或者嘗試在req.params或req.query中傳遞_id:-

如果您通過_id作為req.query:-

您的服務器代碼將類似於:

app.get('/api/category/posts', (req, res) => {
    Post.find({ categoryId: req.query._id }, function(err, posts) {
        res.json(posts);
    });
});

服務檔案

getPosts(_id): Observable<Post[]>{
            return this.http.get<Post[]>(this.apiUrl +"/category/posts"+'?_id='+_id);
              }

component.ts將相同。

如果您想使用post方法檢查req.body,則您的代碼將更改為:

您的服務器代碼將類似於:

app.post('/api/category/posts', (req, res) => {
    Post.find({ categoryId: req.body._id }, function(err, posts) {
        res.json(posts);
    }); });

服務檔案

getPosts(_id): Observable<Post[]>{
            return this.http.post<Post[]>(this.apiUrl +"/category/posts",{_id:_id});
              }

component.ts將相同。

按照REST架構獲取資源,您應該在get request參數中傳遞_id。 您還可以使用簡單的正則表達式模式來驗證id參數,以確保傳遞的id是數字

快速路線

app.get('/api/category/posts/:id(\\d+)', (req, res) => {
    Post.find({ categoryId: req.params.id }, function(err, posts) {
        res.json(posts);
    });
});

服務檔案

getPosts(_id): Observable<Post[]>{
    return this.http.get<Post[]>(`${this.apiUrl}/category/posts/${_id}`);
}

組件文件

this.appService.getPosts(_id)
    .subscribe(data =>this.posts=data);

作為一種好習慣,您還應該跟蹤您的訂閱,並在完成操作或銷毀組件時取消訂閱,或者在first訂閱后使用第first運算符取消訂閱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM