2016-05-09 1 views
0

これに固執し、進める方法がわかりません。私はノードpassport.jsを使用していますpasspost.jsでFacebookの戦略を使用しているとき - ユーザーは返されません

は私の認証にを表明し、Facebookの戦略を使用しています。

伝統的に、データベースにユーザーを保存するときは、findOneを実行してユーザーが存在するかどうかを確認し、そうでない場合は新しいユーザーを作成してそのユーザーを返します。 APIルートを使用して実際の保存を行っていますので、実際の関数ではなくAPIを使用して保存したユーザーをどのように返すのですか?以下

コード:

passport.use(new FacebookStrategy({ 
    clientID: config.facebook.appID, 
    clientSecret: config.facebook.appSecret, 
    callbackURL: config.facebook.callbackURL, 
    profileFields: ['id', 'displayName', 'photos', 'emails', 'birthday', 'location', 'bio', 'likes.limit(100)'] 
}, 
function(accessToken, refreshToken, profile, done){ 
    userModel.findOne({'profileID':profile.id}, function(err, user){ 
     if(user){ 
      done(null, user); 
     } else { 
      request({ 
       url: 'http://localhost:3000/api/user', 
       qs: {id: profile.id}, 
       method: 'POST', 
       json: { 
        fullname: profile.displayName, 
        profilePic: profile.photos[0].value || '', 
        email:  profile.emails[0].value || '', 
        birthday: profile._json.birthday || '', 
        location: profile._json.location.name || '', 
        about:  profile._json.bio || '', 
        likes:  profile._json.likes || '' 
       } 
      }); 

      //What do I put here to return the user like it did earlier using done(null, user); 
    }} 
    ) 
} 
) 
) 

私のルートは、この(動作しますが、私はAPIへのルーティングを経由して、それをやっているように私はそれを返すために、上記の関数を作ることができない)のようになります。

apiRouter.post('/api/user', function(req, res, next){ 
    userModel.findOne({'profileID':req.query.id}, function(err, result){ 
     if(result){ 
      console.log('User exists already'); 
     } else { 
      var newUser = new userModel({ 
       profileID : req.query.id, 
       fullname : req.body.displayName, 
       profilePic : req.body.profilePic || '', 
       email  : req.body.email || '', 
       birthday : req.body.birthday || '', 
       location : req.body.location || '', 
       about  : req.body.about || '', 
       likes  : req.body.likes || '' 
      }); 

      newUser.save(function(err){ 
       console.log('User has been saved'); 
      }) 
     } 
    }) 
}) 

ちなみに、関数に直接保存されているユーザーは機能しますが、ハード面の作業をAPI側(POST呼び出し)で実行したいと考えています。

入力が高く評価されます。

おかげで、 Shayan

答えて

1

はあなたの内部のアプリにあなたの内部のアプリからのHTTPリクエストを作成する必要はありません。 API(ルートなど)は、実際には他のアプリケーションで使用するように設計されています。ロジックはすべてあなたのアプリにあるので、パブリックルータを作る代わりに、 "findOrCreate"コードを自分のモジュール/ファイルに移動して、両方の場所からシームレスに呼び出すことができます。

あなたfindOrCreateは約束を返された場合は、パスポートのコードのようなものを行うことができます。

function(accessToken, refreshToken, profile, done){ 
    userModel.findOrCreate(profile).then(function(user) { 
    done(user); 
    }); 
} 

をそして、あなたがアクセスするブラウザJSのため、後にルートを必要としなければならない、あなたのルートのコードは次のようになります。

function(req, res, next){ 
    userModel.findOrCreate(profile).then(function(user) { 
    res.send(user); 
    }); 
} 
+0

コメントありがとうございました!私は、アプリケーション内でAPIを使用しない方法に戻って、必要に応じて後で外部アプリケーション用に作成します。 –

+1

@ShayanKhan助けてうれしい! –

関連する問題