我正在尝试使用 passport-spotify使用next.js的pages/api(您使用export default (req, res)...
),但我无法将其重定向到Spotify的授权页面。这是我的 pages/api/spotify.js
代码:
var passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
passport.use(
new SpotifyStrategy(
{
clientID: clientid,
clientSecret: clientsecret,
callbackURL: 'http://localhost:3000/auth/spotify/callback'
},
function(accessToken, refreshToken, expires_in, profile, done) {
User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
return done(err, user);
});
}
)
);
export default (req, res, next) => {
passport.authenticate('spotify', {
scope: ['user-read-email', 'user-read-private'],
showDialog: true
}),
res.end()
}
我尝试使用express来测试它,它在那里工作。这是我的代码:
const express = require('express')
const app = express()
const port = 8000
var passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
passport.use(
new SpotifyStrategy(
{
clientID: clientid,
clientSecret: clientsecret,
callbackURL: 'http://localhost:3000/api/callback'
},
function(accessToken, refreshToken, expires_in, profile, done) {
User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
return done(err, user);
});
}
)
);
app.get(
'/auth/spotify',
passport.authenticate('spotify', {
scope: ['user-top-read'],
showDialog: true
}),
function(req, res) {
// The request will be redirected to spotify for authentication, so this
// function will not be called.
}
);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
有没有办法让 Next.js 与 Passport 一起使用?
最佳答案
我明白了!我用过next-connect 。以下是使用 Passport-spotify 和 next.js 的 Spotify 身份验证请求示例:
// pages/api/spotify.js
import nc from 'next-connect';
var passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
passport.use(
new SpotifyStrategy(
{
clientID: clientid,
clientSecret: clientsecret,
callbackURL: 'http://localhost:3000/api/callback'
},
function(accessToken, refreshToken, expires_in, profile, done) {
User.findOrCreate({ spotifyId: profile.id }, function(err, user) {
return done(err, user);
})
}
))
const handler = nc()
.get(passport.authenticate('spotify', {
scope: ['user-top-read']
}), (req, res) => {
})
export default handler;
关于node.js - 如何通过 next.js API 使用 Passport ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63543384/