在Angular从Firebase云函数进行POST调用时发生错误。

huangapple go评论53阅读模式
英文:

Error while doing a POST call from Angular to Firebase Cloud Function

问题

我已经创建了一个Firebase云函数,它正在工作;

export const deleteUser = functions.https.onRequest(async (request, response) => {
  const userEmail = request.body.userEmail;
  await admin.auth().getUserByEmail(userEmail)
    .then(function (userRecord:any) {
      const uid = userRecord.uid;
      admin.auth().deleteUser(uid)
        .then( () => {
          console.log('User deleted');
          response.status(200).send('User deleted');
        })
        .catch(() => {
          console.log('Error deleting user');
          response.status(500).send('Failed to delete user');
        });
    })
    .catch(() => {
      console.log('Error fetching user');
      response.status(500).send('Failed while fetching user');
    })
})

我已经使用Postman进行了检查,一切正常,它按预期从Firebase中删除了用户。
Postman调用的屏幕截图

我从我的组件中调用我的服务,它正常运行。

removeUser(userUid:any, userEmail:any){
    userEmail = {'userEmail': userEmail};
    this.authService.gdelete(userEmail).subscribe();
    // this.usersService.removeUser(userUid);
}

问题出现在我从我的Angular服务中调用云函数时。

gdelete(userEmail:any) {
    //我无法连接帖子与云函数
    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json', 
          'Access-Control-Allow-Origin': '*'
      })
    };
    return this.http.post('https://myfirebaseserver.cloudfunctions.net/deleteUser', {body: userEmail}, httpOptions);
}

它显示以下错误:
浏览器控制台中的错误截图

我认为问题出现在我调用云函数时。我在SO上搜索了很多相关的帖子,并实施了解决方案,但都没有效果。

英文:

I've created a Firebase Cloud Function and it's working;

export const deleteUser = functions.https.onRequest(async (request, response) => {
  const userEmail = request.body.userEmail;
  await admin.auth().getUserByEmail(userEmail)
    .then(function (userRecord:any) {
      const uid = userRecord.uid;
      admin.auth().deleteUser(uid)
        .then( () => {
          console.log('User deleted');
          response.status(200).send('User deleted');
        })
        .catch(() => {
          console.log('Error deleting user');
          response.status(500).send('Failed to delete user');
        });
    })
    .catch(() => {
      console.log('Error fetching user');
      response.status(500).send('Failed while fetching user');
    })
})

I've checked with Postman and everythings is ok, it deletes the user from Firebase as expected.
Screenshot of the call from Postman

I call my service from my component, and works fine.

removeUser(userUid:any, userEmail:any){
    userEmail = {'userEmail': userEmail};
    this.authService.gdelete(userEmail).subscribe();
    // this.usersService.removeUser(userUid);
  }

The problem is when I call the Cloud Funtcion from my Angular Service.

  gdelete(userEmail:any) {
    //no consigo conectar el post con la cloud function 
    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json', 
          'Access-Control-Allow-Origin': '*'
      })
    };
    return this.http.post('https://myfirebaseserver.cloudfunctions.net/deleteUser', {body: userEmail}, httpOptions);
  }

It displays the following error:
Screenshot of the error in the browser console

I think the problem is when I call the cloud function. I've serched on SO lots of posts related and implemented the solutions but nothing worked.

答案1

得分: 0

以下是翻译好的部分:

"Uknown error 0 (in this cases) means CORS are not well set.
Try to add 'cors' npm package to your Function:
npm install cors

Then add these lines:

// Add CORS to your index.TS
const cors = require('cors')({origin: true});

// Put this line to your function
// Automatically allow cross-origin requests
cors(req, res, () => {});

Another error that I can see, you are sending two json level in the body:
{ body: { XXX: XXX } }

on your post in client, just send 'userEmail', like this:

return this.http.post('https://XXXXXXX.cloudfunctions.net/deleteUser', userEmail, httpOptions);```

dont forget to replace the XXX with your server."

<details>
<summary>英文:</summary>

Uknown error 0 (in this cases) means CORS are not well set.
Try to add &#39;cors&#39; npm package to your Function:
npm install cors 

Then add these lines:
```TypeScript
// Add CORS to your index.TS
const cors = require(&#39;cors&#39;)({origin: true});



// Put this line to your function
// Automatically allow cross-origin requests
cors(req, res, () =&gt; {});

Another error that I can see, you are sending two json level in the body:
{ body: { XXX: XXX } }

on your post in client, just send 'userEmail', like this:

return this.http.post(&#39;https://XXXXXXX.cloudfunctions.net/deleteUser&#39;, userEmail, httpOptions);```

dont forget to replace the XXX with your server.



</details>



huangapple
  • 本文由 发表于 2023年5月29日 10:00:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定