我已经在“addUser()”和“loginUser()”中调用了 stClient.login 函数,它们运行良好。我能够将用户添加到我的 MongoDB 数据库并在单击登录时找到用户。(不要担心删除一个)在数据库中找到一个登录用户后,我正在加载一个新的 HTML 页面,在其中传递登录用户的名称和从 MongoDB 检索的配置文件照片。此外,我还想显示登录用户的评论以及姓名和个人资料照片。问题来了:在showComments方法中,我无法访问stitch Client。非常感谢任何帮助。下面是代码:
网页 1:
<!DOCTYPE html>
<html>
<head>
<title>myFb</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig02.js"></script>
</head>
<body onload="onLoadConnectDB()">
<p>Hello My App</p>
<div id="wlcom" align="center">
<button name="adding" onclick="addUser()">Add User</button><br>
<button name="deleting" onclick="deleteUser()">Delete User</button> <br>
<button name="logging" onclick="loginUser()">Login</button><br>
</div>
</body>
</html>
用于 2 个 HTML 的通用 JS:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoadConnectDB(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
});
}
function addUser(){
var n= prompt("Your username: ")
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
// });
alert("added");
}
function deleteUser(){
var d= prompt("Username to delete: ");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.deleteOne({ userName: "Messi" })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
alert("User "+d+ " deleted.");
}
function loginUser(){
var n= prompt("Your username: ");
globalName=n;
const userId = stClient.authedId();
try{
stClient.login().then(()=>
itemsCollection.find({ userName : n }).execute()
).then(docs=>
loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
);
}catch(err){
alert("not found a user");
}
// });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
//document.getElementById("name").value=name;
}else{
//no user in db
alert(name+ " is not found");
}
}
function onLoad () {
//onLoadConnectDB();
var pic;
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
// document.getElementById('pp').value=data.pp;
}
function showComments(globalName){
//ISSUE IS HERE!!
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments + "</div>").join("")
);
};
HTML2
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="assig02.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments" onclick ="showComments()">
Show comments
</div>
</body>
</html>