1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Firebase Cloud Functions】CORS Errorに対応する

Last updated at Posted at 2020-12-28

症状

こちらの動画:【013】Cloud FunctionsとExpressでREST APIの型を作る【Firebase】でFirebaseのcloud functionsの学習を進めておりましたが、Postmanにて、以下のCORS Errorが発生。

CORS Error: The request has been blocked because of the CORS policy

原因

異なるオリジンのリソースへのアクセスに制約がかけられていることが原因。

CORSとは

Cross-Origin Resource Sharing の頭文字を取った略語で、
異なるオリジン間でリソースを共有するための仕組み。

オリジン(origin)はドメイン(domain)と似ていますが、ポート番号も含む形のことを言うそうです。

▼CORSについての詳細はこちら。
なんとなく CORS がわかる...はもう終わりにする。

対策

アクセスに制約がかからないように以下の対応を行います。

  1. corsライブラリをインストール
  2. origin:trueに設定する

1.corsrライブラリをインストール

まずは cors と @types/cors をインストール。

npm install --save cors
npm install --save-dev @types/cors

2.origin:trueに設定する

const cors = require('cors');app.use(cors({ origin: true })); を追加します。

index.ts
import * as functions from 'firebase-functions';
import express from 'express';
import messagesRouter from "./routers/messages/route";
const cors = require('cors');
 
const app = express();
// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
app.use('/', messagesRouter);

export const api = functions
  .region('asia-northeast1')
  .https
  .onRequest(app);

セキュリティ的には問題あるのかな?

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?