TypeError :> ServerResponse.json에서 정의되지 않은 속성 'get'을 읽을 수 없습니까?

Nov 20 2020

RD에서 좋아요를 감지 한 다음 사용자 타임 라인에 광고를 게시하는 간단한 클라우드 기능을 만들려고 할 때 다음과 같은 오류가 발생합니다.

기능을 어떻게 고칠 수 있습니까? 내가 도대체 ​​뭘 잘못하고있는 겁니까?


(아래 2 개의 오류는 Firebase 클라우드 기능 콘솔에서 발생합니다.)

1.

TypeError : ServerResponse.send (/workspace/node_modules/express/lib/response.js)의 ServerResponse.json (/workspace/node_modules/express/lib/response.js:257:20)에서 정의되지 않은 속성 'get'을 읽을 수 없습니다. 158 : 21) likerUIDRef.once.then.catch.error (/workspace/lib/index.js:669:52) at process._tickCallback (internal / process / next_tick.js : 68 : 7)

오류 : process.on.code (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:275)에서 코드 16으로 프로세스가 종료되었습니다. 22) at process.emit (events.js : 198 : 13) at process.EventEmitter.emit (domain.js : 448 : 20) at process.exit (internal / process / per_thread.js : 168 : 15) at Object. process.on.err (/ layers /)에서 sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9) google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js : 271 : 22) at process.emit (events.js : 198 : 13) at process .EventEmitter.emit (domain.js : 448 : 20) at emitPromiseRejectionWarnings (internal / process / promises.js : 140 : 18) at process._tickCallback (internal / process / next_tick.js : 69 : 34)

관련 Typescript :

 function addPersonalizedFYPPosts(whoLikes: string, postUID: string, postID: string) {
      
      //need to use data to fetch my latest likes
      //then I use the likers data to add the new post to his fypTimeline

      const ref = admin.database().ref(`Likes/${postUID}/${postID}/media1`);
      return ref.once("value") 
      .then(snapshot => {

        //use snapshot to get the my latest like ??
        //Now with this ssnapshot we see other people who liked the same post this liker has. get one of their UIDs and see what else they liked add that to thte likers timeline. 

        var i2 = 0

        snapshot.forEach((theChild) => {

          if (i2 == 0) {

            let uid = theChild.key
          
            //do what you want with the uid
  
            //const userWhoAlsoLiked = snapshot.forEach
  
            const likerUIDRef = admin.database().ref(`YourLikes/${uid}`); likerUIDRef.once("value") .then(snap =>{ //const username = snap.val() var i = 0 snap.forEach((child) => { //UserFYP if (i == 0) { let timelineID = child.key; let timeStamp = child.child("timeStamp").val(); let newPostID = child.child("postID").val(); let postUid = child.child("uid").val(); //admin.database().ref(`UserFYP/${whoLikes}/${timelineID}/`).update(["":""]) admin.database().ref(`UserFYP/${whoLikes}/${timelineID}/`).set({"postID": newPostID, "uid": postUid, "timeStamp": timeStamp})
                  .then(slap =>{
                    console.log("Success updating user FYP: " )
                    return Promise.resolve();
                  })
                  .catch(error => {
                    console.log("Error fetching likers username: " + error)
                    response.status(500).send(error);
                  })
                  i++;
                }
                // return;
              })
              
            })
            .catch(error => {
              console.log("Error fetching likers username: " + error)
              response.status(500).send(error)
            })
            
            return;
            
            i2++;
          }
      })

      })
      .catch(error => {
        console.log("The read failed: " + error)
        response.status(500).send(error)
      })  

    }

export const onPostLike = functions.database
.ref('/Likes/{myUID}/{postID}/media1/{likerUID}')
.onCreate((snapshot, context) => {
  const uid = context.params.likerUID
  const postID = context.params.postID
  const myUID = context.params.myUID
  //addNewFollowToNotif(uid, followerUID)

  return addPersonalizedFYPPosts(uid,myUID,postID);
})

최신 정보:

흥미로운 것을 발견했습니다. 다른 클라우드 기능에서도 동일한 2 개의 오류가 발생합니다. 그러나 여전히 작동합니다. 따라서 나는 이러한 오류가 중요하지 않다고 생각합니다. 그러나 문제는 여전히 지속됩니다. UserFYP는 여전히 업데이트되지 않습니다.

업데이트 2 :

이 줄에서 문제를 실패로 좁혔습니다.

        admin.database().ref(`YourLikes/${uid}`).once("value")
        .then(snap =>{

(캐치 블록 실행)

then실행되지 않는지 잘 모르겠습니다 . 내가 얻는 오류 :

Likers 사용자 이름을 가져 오는 중 오류 : 오류 : Reference.update 실패 : 첫 번째 인수에는 'UserFYP.Bke7CYXP31dpyKdBGsiMOEov2q43.0PMdzaOyYBejf1Gh6Pk1RRA5WNJ2.postID.node_.children_.comparator_'속성에 함수가 포함되어 있으며 콘텐츠 = function NAME_COMPARATOR (left, right) {

답변

2 KevWats Nov 26 2020 at 08:32

문제는 기능이 실제로 어떤 이유로 업데이트되지 않는다는 것입니다. 아마도 lib 폴더가 문제 일 수 있습니다. 이 문제를 해결하기 위해 모든 Firebase 함수 파일을 삭제 한 다음 firebase init처음부터 삭제합니다 .

마지막으로 변수가 null이 아닌지 확인하십시오.

          let timeStamp = child.child("timeStamp").val();
          let newPostID = child.child("postID").val();
          let postUid = child.child("uid").val();

이게 맞다면 알려주세요.

1 RafaelLemos Nov 25 2020 at 00:23

timelineID참조 자체에서 참조 로 이동해보십시오 child(). 다음 예와 같습니다.

admin.database()
     .ref(`UserFYP/${whoLikes}`)
     .child(timelineID)
     .set({"postID": newPostID, "uid": postUid, "timeStamp": timeStamp})

이것이 작동하지 않는 경우, 달성하려는 데이터와 데이터 형식을보다 쉽게 ​​확인할 수 있도록 실시간 db 구조를 공유하십시오 (답이 맞으면이 줄을 편집하겠습니다).

TahaMalik Nov 22 2020 at 23:51

이 진술을 수정

let timeStamp = child.child("timeStamp");
let newPostID = child.child("postID");
let postUid = child.child("uid");

에:

let timeStamp = child.child("timeStamp").val();
let newPostID = child.child("postID").val();
let postUid = child.child("uid").val();

설명 :

https://firebase.google.com/docs/reference/node/firebase.database.DataSnapshot#child

여기에서 자식 mehtod는 fireabase가 저장할 수있는 값이 아닌 DocumentSnapshot을 반환합니다.

따라서 값을 반환하는 유일한 방법은 val

https://firebase.google.com/docs/reference/node/firebase.database.DataSnapshot#val