2016-10-13 11 views
0

私のReactJSプロジェクトでは、現在、NodeJSとExpressJSを使用してサーバーを実行しており、MongoClientを使用してMongoDBに接続しています。私は、ユーザーのユーザー名とパスワードで要求を受け付けるログインAPIエンドポイントを設定しました。ユーザーが見つからない場合は、エラーをキャッチしてフロントエンドにエラー(status(500))で応答する必要があります。ReactJS + MongoDB + NodeJS/ExpressJS:process.nextTick(function(){throw err;});とは何ですか?

フロントエンドにjsonエラーで応答するのではなく、サーバーがクラッシュします。私は理由を理解するためにすべてを試しましたが、まだ運がありません。

次のエラーを修正するにはどうすればよいですか?どんな指導や洞察も大いに評価され、答えをアップアップして受け入れます。

私は意図的に、データベースに存在しないユーザー名とパスワード({ username: 'iopsert', password: 'vser'})を要求しました。ここで

は、ログインエンドポイントである:

//login endpoint 
app.post('/api/login/', function(req, res) { 
    console.log('Req body in login ', req.body) 

    console.log('THIS IS WHAT WAS PASSED IN+++++', req._id) 

    db.collection('users').findOne({username: req.body.username}, function(err, user) { 
    console.log('User found ') 

    if(err) { 
     console.log('THIS IS ERROR RESPONSE') 
     // Would like to send this json as an error response to the front-end 
     res.status(500).send({ 
     error: 'This is error response', 
     success: false, 
     }) 
    } 

    if(user.password === req.body.password) { 
     console.log('Username and password are correct') 
     res.status(500).send({ 
     username: req.body.username, 
     success: true, 
     user: user, 
     }) 
    } else { 
     res.status(500).send({ 
     error: 'Credentials are wrong', 
     success: false, 
     }) 
    } 
    }) 

そしてここでは、端末エラーログです:

Req body in login { username: 'iopsert', password: 'vset' } 
THIS IS WHAT WAS PASSED IN+++++ undefined 
User found 
/Users/John/practice-project/node_modules/mongodb/lib/utils.js:98 
    process.nextTick(function() { throw err; }); 
           ^

TypeError: Cannot read property 'password' of null 
    at /Users/John/practice-project/server/server.js:58:12 
    at handleCallback (/Users/John/practice-project/node_modules/mongodb/lib/utils.js:96:12) 
    at /Users/John/practice-project/node_modules/mongodb/lib/collection.js:1395:5 
    at handleCallback (/Users/John/practice-project/node_modules/mongodb/lib/utils.js:96:12) 
    at /Users/John/practice-project/node_modules/mongodb/lib/cursor.js:675:5 
    at handleCallback (/Users/John/practice-project/node_modules/mongodb-core/lib/cursor.js:165:5) 
    at setCursorNotified (/Users/John/practice-project/node_modules/mongodb-core/lib/cursor.js:505:3) 
    at /Users/John/practice-project/node_modules/mongodb-core/lib/cursor.js:578:16 
    at queryCallback (/Users/John/practice-project/node_modules/mongodb-core/lib/cursor.js:226:18) 
    at /Users/John/practice-project/node_modules/mongodb-core/lib/connection/pool.js:430:18 

そして/Users/John/practice-project/node_modules/mongodb/lib/utils.js:98は以下を参照している:

var handleCallback = function(callback, err, value1, value2) { 
    try { 
    if(callback == null) return; 
    if(value2) return callback(err, value1, value2); 
    return callback(err, value1); 
    } catch(err) { 
    process.nextTick(function() { throw err; }); 
    return false; 
    } 

    return true; 
} 

EDIT

ここで

は、サーバーにインポートされているすべてのとおりです。

"use strict" 

var express = require('express'); 
var path = require('path'); 
var config = require('../webpack.config.js'); 
var webpack = require('webpack'); 
var webpackDevMiddleware = require('webpack-dev-middleware'); 
var webpackHotMiddleware = require('webpack-hot-middleware'); 
var bodyParser = require('body-parser'); 
var MongoClient = require('mongodb').MongoClient; 
var ObjectId = require('mongodb').ObjectID; 
const jwt = require('jsonwebtoken') 

var app = express(); 
var db; 

var compiler = webpack(config); 

app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath})); 

app.use(webpackHotMiddleware(compiler)); 

app.use(express.static('dist')); 

app.use(bodyParser.json()); 

そして、これは要求が行われると、エラーがキャッチされた方法です。

loginUser(creds) { 
    var request = { 
     method: 'POST', 
     headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
     }, 
     body: JSON.stringify(creds), 
    } 

    fetch(`http://localhost:3000/api/login`, request) 
    .then(res => res.json()) 
    .then(user => { 
     console.log(user); 
     console.log('Successful') 
    }) 
    .catch(err => { 
     console.log('Error is', err) 
    }) 
    }, 
+0

'user'または' req.body'が定義されていないようです。あなたのプロジェクトに** bodyParser **を含めましたか? – adeneo

+0

@adeneoはい、元の投稿の編集を見てください。存在するユーザ名とパスワードでリクエストを渡すと、正しい 'user'と' req.body'が記録され、if文が入力されます。 –

答えて

1

エラーがスローされているようですが、私には見えますuserが定義されていないためです。

if(user.password === req.body.password) {...} 

コンソールステートメントをより詳しく見てください。

1. Req body in login { username: 'iopsert', password: 'vset' } 
2. THIS IS WHAT WAS PASSED IN+++++ undefined 
3. User found 
4. /Users/John/practice-project/node_modules/mongodb/lib/utils.js:98 
5. process.nextTick(function() { throw err; }); 
          ^
6. TypeError: Cannot read property 'password' of null 
7. at /Users/John/practice-project/server/server.js:58:12 

2行目はreq._idあなたはエラーがあるかどうかを確認する前に、またはユーザーが実際に存在するかどうかあなたのUser found文が印刷されundefined

であることを示しているので、そこに実際にあることの代表ではありませんユーザー。

行6は、ヌルオブジェクトからpasswordのプロパティを読み取ろうとしているため、エラーがスローされていることを示しています。

//login endpoint 
app.post('/api/login/', function(req, res) { 
    console.log('Performing login with req.body='); 
    console.log(JSON.stringify(req.body, null, 4)); 

    // check for username 
    if (!req.body.username) { 
    return res.status(401).send({message: 'No username'}); 
    } 

    // find user with username 
    db.collection('users').findOne({username: req.body.username}, function(err, user) { 

    // handle error 
    if(err) { 
     console.log('Error finding user.'); 
     return res.status(500).send({message: 'Error finding user.'}); 
    } 

    // check for user 
    if (!user) { 
     console.log('No user.'); 
     return res.status(500).send({message: 'No user.'}); 
    } 
    console.log('User found.'); 

    // check password 
    if(user.password !== req.body.password) { 
     console.log('Wrong password.'); 
     return res.status(401).send({message: 'Wrong password.'}); 
    } 

    // return user info 
    return res.status(200).send(user); 
    }); 

いくつかの最終的な思考:私はもっとこのように見えるためにあなたのログインロジックを変更するお勧めします


  • がエラーを処理することを確認します(存在する場合)と続行する前にuserが存在することを確認してください。
  • return res.status(...).send(...)ステートメントには常にreturnが含まれています。そうしないと、後続のコードが実行されます。
  • パスワードを単純な文字列として保存することは、一般的にはお勧めできません。それらを暗号化するための作業。 passportまたはbcryptをご覧ください。

これが役に立ちます。

+0

申し訳ありませんが、実際にはreq._idは存在しません。要求が合格しなかったからです。無視してください。ユーザーが実際にデータベースに存在する場合、ティックエラーも発生しないので、ユーザーが見つからない場合、エラー応答を適切に処理していないと仮定していますか?また、findOne()を実行して関数を入力すると、ユーザー名が見つかったことを意味していませんか?ユーザーを再度確認する必要はありますか?それは 'user.username'ではありませんか?そのオブジェクトが 'username'と' password'を持っていないので、なぜ '!user'が意味するのでしょうか?助けてくれてありがとうございます –

+0

ちょうど試しましたが、実際にはエラーではなく、オブジェクト '({message:" No user "})を記録するフロントエンドとコンソールから' response'として渡されます。 'catch()'関数で 'error'と捕捉されました。 'catch()'関数をキャッチするためにフロントエンドから何かが欠けている可能性がありますか? –

+0

あなたが最後のコメントを見たかどうかを確認するだけです。私にお知らせください。 –

関連する問題