2017-10-14 5 views
0

私はSpotifyのAPIで認証するアプリケーションを開発中です。私はpassport-spotifyを使っています。自分のルートルートにあるセッションID(/)にアクセスできる必要があります。Expressでリクエストオブジェクトのルート間でデータを共有するにはどうすればよいですか?

私は/callbackの認証の後、SpotifyでセッションIDを設定できますが、セッションIDは/にはアクセスできません。誰かが私が認証した後req.session.id/にアクセスできるようにExpressのルート間でデータを渡す方法を教えてください。

私はここに私のエンドポイントを共有します:

/

app.get('/', cors(), (req, res) => { 
    if (req.session.id != null) { 
    res.json({isAuthenticated: true }) 
} else { 
    res.json({isAuthenticated: false, message: 'Please log in.' }) 
} 

})

パスポート戦略

passport.use(new SpotifyStrategy({ 
    clientID: clientId, 
    clientSecret: clientSecret, 
    callbackURL: CALLBACK_URL 
}, 
    (accessToken, refreshToken, profile, done) => { 
    process.nextTick(function() { 
     let user = { spotifyId: profile.id, access_token: accessToken, 
     refresh_token: refreshToken } 
     return done(null, user) 
    }) 
    })) 

/auth/spotify

app.get('/auth/spotify', 
    passport.authenticate('spotify', {scope: ['user-read-email', 'user- 
    read-private'], showDialog: true}), 
    (req, res) => { 
}) 

/callback

app.get('/callback', passport.authenticate('spotify', { 
    failureRedirect: '/', successRedirect: FRONTEND_URL }), (req, res, 
    next) => { 
    req.session.id = req.user.spotifyId 
    localStorage.setItem('access_token_' + req.session.id, 
    req.user.access_token) 
    localStorage.setItem('refresh_token_' + req.session.id, 
    req.user.refresh_token) 
    return next(null, req.session.id) 
}) 

答えて

0

あり、あなたの質問をした方法でデータを共有する方法はありません、そしてその理由は、彼らは2つの異なるreqオブジェクトであり、非常に簡単です。

あなたが何ができるか、別のmiddlware関数を定義し、このようなものです:

function middlware(req, res, next) { 
    req.session.id = req.user.spotifyId; 
    next(); 
} 

そして、あなたが楽しんでるのmiddlware後middlwareとしてあなた敗走の両方で、その関数を呼び出します。

関連する問題