FirebaseHosting + CloudFunctionsでクライアントのIPを取得する方法
複雑な家庭の事情でどうしてもfirebaseを使いつつクライアントのIPアドレスを取得しなくてはならなかったのでメモ。
前提として、フロントはNUXTでつくってます。
バックエンド(CloudFunctions側)
/functions/index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.getIp = functions.https.onCall((data, context) => {
const clientIp = context.rawRequest.headers['x-appengine-user-ip'];
return clientIp;
});
- firebase内でのリクエストなのでfunctions.https.onCall()を使用
- onCall((data, context)
- dataにはリクエスト時に投げた値が入りますが、今回は何も投げません
- contextにはリクエストする側の認証情報が入ります
- 詳しくは公式説明で
- context.rawRequest.headers['x-appengine-user-ip']でIPが取得できます
- リクエストヘッダーの値についての詳しい情報も公式説明で
フロントエンド(NUXT側)
/pages/index.vue
created() {
const getIp = firebase.functions().httpsCallable("getIp");
getIp().then((response) => {
console.log(response)
});
},
- httpsCallableで関数を指定
- ページ読み込んだらすぐに確認できるようcreatedに書いてます
Author And Source
この問題について(FirebaseHosting + CloudFunctionsでクライアントのIPを取得する方法), 我々は、より多くの情報をここで見つけました https://qiita.com/aktkro/items/1923ba059afd8b1fa091著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .