繁体   English   中英

如何通过 Next.js(带有 Typescript)应用程序调用经过身份验证的 HTTP 触发器 Google Cloud Function?

[英]How Do I Call An Authenticated HTTP Trigger Google Cloud Function Via A Next.js (with Typescript) App?

我创建了一个 Google Cloud Platform 帐户,并制作了一个简单的 hello_world 类型 Python “Cloud Function”,它只会吐出一些简单的文本。 我使这个 function“HTTP”可访问,并且只能由我为调用这个 function 而创建的“服务帐户”调用/验证。我为此“服务帐户”生成了一个密钥并下载了 json 文件钥匙。

问题是我找不到任何关于如何在 next.js 应用程序中使用我的服务帐户调用此 function 的文档。 我试过这个:

import React from 'react';
import { Button } from 'react-bootstrap';
import { GoogleAuth } from 'google-auth-library';

const projectId = 'gtwitone';
const keyFilename = '/Users/<myusername>/path/to/cloudfunction/credentials.json';

class Middle extends React.Component {
    handleClick() {
        console.log('this is:', this);
      }
    // This syntax ensures `this` is bound within handleClick.  // Warning: this is *experimental* syntax.  handleClick = () => {    console.log('this is:', this);  }

    /* async listFunctions() {
        const [functions] = await client.listFunctions();
        console.info(functions);
    } */

    async runGoogleCloudFunctionTest() {
      // Define your URL, here with Cloud Run but the security is exactly the same with Cloud Functions (same underlying infrastructure)
      const url = "https://us-central1-<projectname>.cloudfunctions.net/<functionname>"
      //Example with the key file, not recommended on GCP environment.
      const auth = new GoogleAuth({keyFilename: keyFilename})
  
      //Create your client with an Identity token.
      const client = await auth.getIdTokenClient(url);
      const res = await client.request({url});
      console.log(res.data);
    }

    render() {
      return (
        <div className="col-md-12 text-center">
            <Button variant='primary' onClick={this.runGoogleCloudFunctionTest}>
                Click me
            </Button>
        </div>
      );
    }
  }

export default Middle;

但是我的终端出现了这个错误:

<myusername>@<mycomputername> <thisnextjsappdirectory> % yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
wait  - compiling...
event - compiled client and server successfully in 267 ms (124 modules)
wait  - compiling / (client and server)...
wait  - compiling...
error - ./node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'

Import trace for requested module:
./node_modules/google-auth-library/build/src/index.js
./components/Middle.tsx
./pages/index.tsx

https://nextjs.org/docs/messages/module-not-found
Native Node.js APIs are not supported in the Edge Runtime. Found `child_process` imported.

Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json
^C
<myusername>@<mycomputername> <thisnextjsappdirectory> % 

我知道这是我的 Next.js 应用程序中服务器端呈现的问题,人们建议使用客户端 package 像这样https://github.com/google/google-api-javascript-client 但是google-api-javascript-client没有任何关于使用.json凭据文件而不是我没有的API KEY进行身份验证的文档。

简而言之,我如何让我的应用程序运行并运行 Google Cloud function 以及经过身份验证的服务帐户的.json凭据文件?

我通过简单地将GoogleAuth api 调用移动到pages/api路由来修复它。

页面/api/google.ts

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next"
import { GoogleAuth } from "google-auth-library"

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    const url = process.env.FUNCTION_URL as string

    //Example with the key file, not recommended on GCP environment.
    const auth = new GoogleAuth({ keyFilename: process.env.KEYSTORE_PATH })

    //Create your client with an Identity token.
    const client = await auth.getIdTokenClient(url)
    const result = await client.request({ url })
    console.log(result.data)
    res.json({ data: result.data })
}

组件/Middle.tsx

import React from "react"
import { Button } from "react-bootstrap"

class Middle extends React.Component {
  handleClick() {
        console.log("this is:", this)
    }
  
  // this talks with /pages/api/google
  async imCallingAnAPI() {
    const result = await fetch("/api/google")
    console.log({ result })
  }

  render() {
    return (
      <div className="col-md-12 text-center">
        <Button variant="primary" onClick={this.imCallingAnAPI}>
          Click me
        </Button>
      </div>
    )
  }
}

export default Middle

页面/index.tsx

import type { NextPage } from 'next'
import Header from '../components/Header';
import Footer from '../components/Footer';
import Middle from '../components/Middle';

const Home: NextPage = () => {
  return (
    <><main className='d-flex flex-column min-vh-100'>
      <Header />
      <br></br>
      <br></br>
      <Middle />
      </main>
      <footer>
        <Footer />
      </footer>
    </>
  )
}

export default Home

我认为 next.js 在组件中加载GoogleAuth时遇到问题。 我不是 100% 确定为什么,但我认为这与 next.js 不知道如何通过服务器端呈现来处理GoogleAuth有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM