[英]How to get host in app.js for use in determining environment (production/development)
我正在嘗試獲取應用程序當前所在的主機,然后相應地更改變量。 我知道我可以使用req.get('host')
來獲取主機,但是我認為我的問題源於回調
var callBackUrl;
app.use(function(req,res,next){
if(req.get('host') == 'localhost:3000'){
callBackUrl = 'http://localhost:3000/handleauth';
}
else{
callBackUrl = 'http://example.com/handleauth';
}
console.log('CALL BACK URL: ', callBackUrl);
next();
});
console.log(callBackUrl); //undefined
app.use('/', routes);
... //more code
我想做一個記錄,說明我已閱讀有關異步性的內容,並了解為什么console.log
打印undefined
。 我根本不知道如何將回調與req
和res
綁定在一起。
req.host
正確返回一個值。 我只需要獲取當前主機,然后將其用於身份驗證目的(生產與開發)
編輯:也許此附加代碼將幫助其他人理解我要完成的工作
//... original code from question
passport.use(new InstagramStrategy({
clientID: INSTAGRAM_CLIENT_ID,
clientSecret: INSTAGRAM_CLIENT_SECRET,
callbackURL: callBackUrl //set to undefined and therefore authentication fails
},
function(accessToken, refreshToken, profile, done){
process.nextTick(function(){
app.set('instaID', profile.id.toString());
app.set('fullName', profile.displayName);
app.set('imgSource', profile._json.data.profile_picture);
return done(null,profile.id);
});
}));
我認為您應該使用其他類似方式;
var callBackUrl;
app.use(function(req,res,next){
if(req.get('host') == 'localhost:3000'){
callBackUrl = 'http://localhost:3000/handleauth';
console.log('CALL BACK URL: ', callBackUrl);
next();
}
else{
callBackUrl = 'http://example.com/handleauth';
console.log('CALL BACK URL: ', callBackUrl);
next();
}
});
console.log(callBackUrl); //undefined
app.use('/', routes);
... //more code
通過將所有身份驗證代碼移到app.use
回調中,我能夠解決此問題。 如果有人有其他解決方案,請告訴我。 對於我來說,將整個代碼塊粘貼在那里只是為了訪問一個變量的值對我來說似乎很奇怪。
var callBackUrl;
app.use(function(req,res, next){
if(req.get('host') == 'localhost:3000'){
callBackUrl = 'http://localhost:3000/handleauth';
}
else{
callBackUrl = 'http://example.com/handleauth';
}
console.log('CALL BACK URL: ', callBackUrl);
passport.serializeUser(function(user,done){
done(null,user);
});
passport.deserializeUser(function(obj,done){
done(null,obj);
});
passport.use(new InstagramStrategy({
clientID: INSTAGRAM_CLIENT_ID,
clientSecret: INSTAGRAM_CLIENT_SECRET,
callbackURL: callBackUrl //no longer undefined
},
function(accessToken, refreshToken, profile, done){
process.nextTick(function(){
app.set('instaID', profile.id.toString());
app.set('fullName', profile.displayName);
app.set('imgSource', profile._json.data.profile_picture);
return done(null,profile.id);
});
}));
next();
});
console.log("URL: ", callBackUrl) //still prints undefined but that it ok since we use the value of callBackUrl inside the callback
app.use('/', routes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.