req.bodyのフィールドの長さを取得する必要があります。しかしreq.body.username.length <= 5
を使って私はエラーCannot read property 'length' of undefined
を得ました。どうしたらいいですか?ノードJS取得リクエストボディ長
0
A
答えて
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.
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
エラーは、ユーザー名ですか?ユーザー名を確実に取得する必要があります。 あなたが取得しているので最初にログアウトします req.body && req.body.username –
ユーザ名が配列の場合は、長さが返されます –