2017-07-14 4 views
0

私はいくつかのPOSTリクエストを処理するためにExpressルータ機能を使用しています。私はjwtVerify機能で、サーバー側でクライアント側から送信されたデータにアクセスすることはできませんExpressルータのポストリクエストで 'body'にアクセスできない

const express = require('express'); 
const app = express(); 
const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 

class HTTPServer { 
    constructor(credentials, app) { 
     this.app = app; 
     this.specifyRoutes(); 
    } 

    specifyRoutes() { 
     this.router = express.Router(); 
     this.router.use((req, res, next) => this.jwtVerify(req, res, next)); 
     this.app.use('/api', this.router); 
     this.router.post('/get-preferences', this.getPref); 
    } 

    jwtVerify(req, res, next) { 
     console.log(req.body); // This prints "undefined". 
     next(); 
    } 
} 

Client.js

let data = { 
    endpoint: "Blah Blah"; 
}; 

return fetch('/api/get-preferences/', { 
    method: 'POST', 
    headers: { 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify(data) 
}); 

Server.jsこれが修正されたら、そのデータを/get-preferencesルートのgetPref関数に渡したいと思います。

+1

'this.app.useは何( '/ API'、this.router(REQ、RES))'行うことになって? – robertklep

+0

@robertklep実際には、 'this.app.use( '/ api'、this.router(req、res));'ステートメントの後ろに文がいくつかあります。したがって、 '/ api /'のルートをチェックし、それをその下のステートメントに転送するだけです。 –

+0

'req'と' res'はどこから来ますか?また、「これ」とは何ですか? – robertklep

答えて

0

ここに2つの問題があります。まず、更新:

this.app.use(bodyParser.json()); 

第二:

this.app.use('/api', this.router); 
+0

実際、 'app.use(bodyParser.json());'はルートと同じクラスにはありません。それはグローバルです。 –

+0

そして、私は2番目のものを更新しました。要求の本文を印刷するとまだ未定義と表示されます。 –

+0

@AnirudhGoelは、HTTPServerクラスのインスタンスを作成する方法を示しています。 – Lazyexpert

関連する問題