云功能Cors错误"对预检请求的响应没有通过访问控制检查"

时间:2018-02-17 10:37:18

标签: firebase express cors google-cloud-functions

我有一个简单的firebase设置和离子应用程序。我已经尝试了几天让云功能正常工作。但是这个错误似乎并没有消失:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-my-app.cloudfunctions.net/savedProfiles. (Reason: CORS preflight channel did not succeed).

从前端我有这个:

let token = this.auth.user.getIdToken();

    const httpOptions = {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
        'Accept':'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}` })
      };

    this.httpClient.get('https://us-central1-my-app.cloudfunctions.net/savedProfiles', httpOptions)
    .subscribe(data => {
      console.log(data);
  });

我的云功能如下:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({
  origin: true,
  allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'],
  methods: ['OPTIONS', 'GET', 'PUT', 'POST', 'DELETE']
});
const app = express();

// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const validateFirebaseIdToken = (req, res, next) => {

  console.log('Check if request is authorized with Firebase ID token');


  if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
      !req.cookies.__session) {
    console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
        'Make sure you authorize your request by providing the following HTTP header:',
        'Authorization: Bearer <Firebase ID Token>',
        'or by passing a "__session" cookie.');

    res.set('Access-Control-Allow-Origin', '*')
       .set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
       .status(403).send('Unauthorized');
    return;
  }

  let idToken;
  if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
    console.log('Found "Authorization" header');
    // Read the ID Token from the Authorization header.
    idToken = req.headers.authorization.split('Bearer ')[1];
  } else {
    console.log('Found "__session" cookie');
    // Read the ID Token from cookie.
    idToken = req.cookies.__session;
  }

  admin.auth().verifyIdToken(idToken).then((decodedIdToken) => {
    console.log('ID Token correctly decoded', decodedIdToken);
    req.user = decodedIdToken;
    return next();
  }).catch((error) => {
    console.error('Error while verifying Firebase ID token:', error);
    res.set('Access-Control-Allow-Origin', '*')
       .set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
       .status(403)
       .send('Unauthorized');
  });
};


app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/savedProfiles', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*')
     .set('Access-Control-Allow-Methods', 'OPTIONS, POST, GET, PUT')
     .send(`Hello ${req.user.name}`);
});

// This HTTPS endpoint can only be accessed by your Firebase Users.
// Requests need to be authorized by providing an `Authorization` HTTP header
// with value `Bearer <Firebase ID Token>`.
exports.savedProfiles = functions.https.onRequest(app);

这与此处的示例代码类似:https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint

我确信解决方案很简单,但我似乎无法理解发生了什么。我以为app.use(cors);应该排除这些问题?如果我没有添加res.set('Access-Control-Allow-Origin', '*'),那么我会得到一个

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-my-app.cloudfunctions.net/savedProfiles. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

错误。从控制台日志返回到我的控制台的错误是:

error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: false, … }
headers: Object { normalizedNames: Map, lazyUpdate: null, headers: Map }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null

如果您希望我扩展错误,请告诉我。感谢

1 个答案:

答案 0 :(得分:-1)

您需要在cors函数中的初始化函数AND之前添加express

'use strict';

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors';
import * as express from 'express';

cors({
  origin: true,
}); // << for bootstrap 
admin.initializeApp(functions.config().firebase);

const app = express();
app.use(cors()); // << for what you just defined

这应该可以正常工作