Javascript 说明如何将值从.js promise传递到.ejs视图
我试图将一个值从路由js文件(auth.js)传递到ejs视图(dashboard.ejs) 这是auth.js中的代码:Javascript 说明如何将值从.js promise传递到.ejs视图,javascript,node.js,express,routes,ejs,Javascript,Node.js,Express,Routes,Ejs,我试图将一个值从路由js文件(auth.js)传递到ejs视图(dashboard.ejs) 这是auth.js中的代码: const express = require("express"); const google = require('googleapis').google; const jwt = require('jsonwebtoken'); const CONFIG = require("../config/passport-google"
const express = require("express");
const google = require('googleapis').google;
const jwt = require('jsonwebtoken');
const CONFIG = require("../config/passport-google");
const nf = require('node-fetch');
const router = express.Router();
// Google's OAuth2 client
const OAuth2 = google.auth.OAuth2;
router.get("/youtube", function(req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(
CONFIG.oauth2Credentials.client_id,
CONFIG.oauth2Credentials.client_secret,
CONFIG.oauth2Credentials.redirect_uris[0]
);
// Obtain the google login link to which we'll send our users to give us access
const loginLink = oauth2Client.generateAuthUrl({
access_type: "offline", // Indicates that we need to be able to access data continously without the user constantly giving us consent
scope: CONFIG.oauth2Credentials.scopes // Using the access scopes from our config file
});
return res.render("./home/g-login", { loginLink: loginLink });
});
router.get("/youtube/callback", function(req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(
CONFIG.oauth2Credentials.client_id,
CONFIG.oauth2Credentials.client_secret,
CONFIG.oauth2Credentials.redirect_uris[0]
);
if (req.query.error) {
// The user did not give us permission.
return res.redirect("/");
} else {
oauth2Client.getToken(req.query.code, function(err, token) {
if (err) return res.redirect("/");
// Store the credentials given by google into a jsonwebtoken in a cookie called 'jwt'
res.cookie("jwt", jwt.sign(token, CONFIG.JWTsecret));
// return res.redirect("/get_some_data");
if (!req.cookies.jwt) {
// We haven't logged in
return res.redirect("/");
}
// Add this specific user's credentials to our OAuth2 client
oauth2Client.credentials = jwt.verify(req.cookies.jwt, CONFIG.JWTsecret);
// Get the youtube service
const service = google.youtube("v3");
const url = `https://www.googleapis.com/oauth2/v1/userinfo?access_token=${token[Object.keys(token)[0]]}`;
const get_data = async () => {
try {
const response = await nf(url);
const json = await response.json();
return await json;
} catch (error) {
console.log(error);
}
};
const diomerda = get_data();
module.exports = {
diomerda
}
// Get 50 of the user's subscriptions (the channels they're subscribed to)
service.subscriptions
.list({
auth: oauth2Client,
mine: true,
part: "snippet,contentDetails",
maxResults: 50
})
.then(response => {
//console.log(response.data.items[0].snippet.resourceId)
// Render the profile view, passing the subscriptions to it
return res.render("./user/dashboard", { subscriptions: response.data.items, diomerda: diomerda });
});
});
}
});
// Logout from Google
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
})
module.exports = router;
diomerda变量是一个承诺,我已经通过service.subscriptions下面的函数呈现了视图(它正确地将订阅值发送到仪表板视图),那么我如何将我的diomerda变量传递给该视图呢
我正在尝试使用module.exports
,正如您在代码中看到的那样,但似乎我无法在ejs文件中使用require
dashboard.ejs是:
<h6>Profile dashboard</h6>
<h3>Welcome</h3>
<p>Here are your favorites channels</p>
<% var params = require('../routes/auth')
console.log(params.diomerda);
%>
Profile仪表板
欢迎
这是你最喜欢的频道
请在以下代码中找到标记1和标记2
mark1:您不需要导出此方法,只需在呈现ejs视图之前使用它即可。当您在这个函数中返回json时,不需要在这里添加额外的wait
mark2:我将get_data
函数放在这里,因为我看到您在router.get(“/youtube/callback”)
中的代码末尾向用户呈现EJB。因此,在将ejs视图呈现给用户之前,需要调用get_data
函数来获取所需的数据。然后,用数据渲染它
router.get(“/youtube/callback”),函数(req,res){
//从配置文件中的凭据创建OAuth2客户端对象
const oauth2Client=新OAuth2(
CONFIG.oauth2Credentials.client_id,
CONFIG.oauth2Credentials.client_secret,
CONFIG.oauth2Credentials.redirect_uris[0]
);
if(请求查询错误){
//用户没有给我们权限。
返回res.redirect(“/”);
}否则{
oauth2Client.getToken(req.query.code,函数(err,token){
if(err)返回res.redirect(“/”);
//将google提供的凭据存储到名为“jwt”的cookie中的jsonwebtoken中
res.cookie(“jwt”,jwt.sign(token,CONFIG.JWTsecret));
//return res.redirect(“/get_some_data”);
如果(!req.cookies.jwt){
//我们还没有登录
返回res.redirect(“/”);
}
//将此特定用户的凭据添加到OAuth2客户端
oauth2Client.credentials=jwt.verify(req.cookies.jwt,CONFIG.JWTsecret);
//获取youtube服务
const service=google.youtube(“v3”);
常量url=`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${token[Object.keys(token)[0]]}`;
//======================标记1====================
const get_data=async()=>{
试一试{
常量响应=等待nf(url);
const json=await response.json();
返回json;
}捕获(错误){
console.log(错误);
}
};
//获取50个用户订阅(他们订阅的频道)
服务订阅
.名单({
作者:oauth2Client,
我的:是的,
部分:“代码片段,内容详细信息”,
最大结果:50
})
//=========================标记2====================
//记住在这里添加异步
.then(异步(响应)=>{
//=========================标记2====================
const diomerda=等待获取数据()
//呈现纵断面图,并向其传递订阅
返回res.render(“./user/dashboard”,{subscriptions:response.data.items,diomerda:diomerda});
});
});
}
});
Hi,您在服务订阅中所说的“//require”是什么意思,“service.subscriptions”已经在auth.js中,上面的所有代码都在auth.js中。“service”是一个声明在我显示的代码正上方的变量,const service=google.youtube(“v3”);因为我在auth.js中需要“googleapis”,所以我认为它是不同的文件。你能粘贴完整的js文件吗?用完整的代码编辑。我这样做的原因是因为youtube v3 api不返回用户信息,所以我必须使用从youtube oauth获得的令牌,并使用它进行用户信息api调用,异步js shitfest begunI更新了我的答案。