2016-05-04 18 views
0

req.bodyのフィールドの長さを取得する必要があります。しかしreq.body.username.length <= 5を使って私はエラーCannot read property 'length' of undefinedを得ました。どうしたらいいですか?ノードJS取得リクエストボディ長

+1

エラーは、ユーザー名ですか?ユーザー名を確実に取得する必要があります。 あなたが取得しているので最初にログアウトします req.body && req.body.username –

+0

ユーザ名が配列の場合は、長さが返されます –

答えて

0

ミドルウェアbody-parserを使用して本文を解析し、その中のデータにアクセスする必要があると思います。

コマンドを使用して、それをインストールします。

var bodyParser = require('body-parser'); 

app.use(bodyParser.urlencoded({extended: true})); // Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings. 

app.use(bodyParser.json()); // Returns middleware that only parses json. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings. 

NPMリファレンス:https://www.npmjs.com/package/body-parser

+0

私はapp.jsで使用しましたがdidn; t作業 – NoName2

+0

@NoName任意のエラー? –

+0

私はそれを関数の中で使うことに言及することを忘れてしまいます。私はrouter.post()の中で使うことができます。エラーは '不定のプロパティ '長さ'を読むことができません' – NoName2

0

この問題は、二つの可能性を持つことができます

npm install body-parser 

はこのようにそれを使用してください。

1)req.bodyは未定義です。それはあなたが体を解析することができないことを意味します。これを克服するには、次のステップを実行します。

npm install body-parser --save 

はあなたreq.bodyが正しく解析されていますがREQにユーザ名という名前のキーを持っていけない場合、私が考えることができる

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.set('json spaces', 1); 

2.Another可能性がある、あなたのapp.jsに次の行を含めます.body

関連する問題