簡體   English   中英

如何從 Node JS 中的 Google Cloud Function 中的雲 SQL 中讀取數據

[英]How to read data form cloud SQL in Google Cloud Function in Node JS

我是 Google Cloud Function 的新手,我在這里嘗試從雲 SQL 加載數據,因為我編寫了一個代碼,它具有數據庫連接以及 SQL 查詢字符串但是當我嘗試測試 function 時,它拋出錯誤或 Object或者有時它說您沒有返回任何數據。 我嘗試了很多發送數據的方法,但仍然對我不起作用。 提前致謝。

代碼片段,

exports.welcome = async (req, res) => {
  const tag = req?.body?.fulfillmentInfo?.tag;
  let message = tag || req?.query?.message || req?.body?.message || 'Hello World!';

  const pool = mysql.createPool({
    connectionLimit: 1,
    host: '10.30.48.2',
    user: 'root',
    password: 'TEST@TEST',
    database: 'hospital_assist'
  });
  
  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [`Welcome entry point ${message}`],
          },
        },
      ],
    },
  };

  let qResult = await pool.query('SELECT * FROM Patients;');
  // pool.query('SELECT * FROM Patints', (error, result) => {
  //   console.log(error);
  //   console.log(result);
  //   console.log('In loop');
  //   res.status(200).send(jsonResponse);  
  // });



  // await pool.query('select * from Patients;', (error, results) => {
  //       if (error) {
  //           console.log(error);
  //           res.status(200).send(jsonResponse);
  //       }
  //       qResult = results;
  //       // res.send(results);
  //   });

  console.log(qResult);
  console.log(`In loop ${qResult}`);
  res.status(200).send(JSON.stringify(qResult)); 

  // res.status(200).send(jsonResponse);
};

如果您嘗試使用公共 IP 連接到您的實例,則需要指定 Unix 套接字路徑,例如,

mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: "/cloudsql/my-project:us-central1:my-instance",
    // Specify additional properties here.
    ...config,
});

有關詳細信息,請參閱文檔

對於您的情況,您有幾種解決方案,特別推薦 2 種:

  • 使用內部 IP(您當前的代碼)。 使用該模式,您可以刪除公共 IP 並從 inte.net 中完全隱藏數據庫。 要允許 CLoud Functions 訪問私有 IP,您必須在無服務器世界(服務器和網絡由 Google Cloud 為您管理,因此您不在您的 VPC 中)與您的項目世界(尤其是您的 VPC數據庫已連接)。 無服務器 VPC 連接器已為此完成。
  • 借助 Cloud Functions,您可以將內置連接器與 Cloud SQL MySQL (僅在版本 8 中)一起使用。 它打開一個 linux 套接字,您必須使用支持該套接字通信模式的驅動程序/庫。 這里的優勢是通過內置連接器對數據庫通信進行加密。

注意:使用 Cloud SQL public IP 避免在您的 Cloud SQL 數據庫上使用 authorized.network 以保持良好的安全級別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM