用于firebase返回响应的云函数500

时间:2017-04-25 05:36:42

标签: javascript ajax firebase google-cloud-functions

这是我调用的功能

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cors = require('cors')({origin: true});
const router = new express.Router();

 router.use(cors);  
 router.get('*', (req, res) => {
      res.setHeader('Access-Control-Allow-Origin', '*').status(200)
            .send('Hello, Functions');
    });

exports.date = functions.https.onRequest(router);

但是我收到了这个错误:

  

XMLHttpRequest无法加载   https://us-central1-idntt-baed5.cloudfunctions.net/date。没有   '访问控制允许来源'标题出现在请求的上   资源。起源' https://idntt-baed5.firebaseapp.com'因此   不允许访问。响应的HTTP状态代码为500。

3 个答案:

答案 0 :(得分:1)

您正在尝试执行的操作的正确代码是:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Start writing Firebase Functions
// https://firebase.google.com/functions/write-firebase-functions

exports.date = functions.https.onRequest((request, response) => {
    response.send("Hello, Functions");
})

现在你应该喜欢这个https://us-central1-idntt-baed5.cloudfunctions.net/date

并且您不允许使用Access-Control-Allow-Origin

答案 1 :(得分:1)

您正在尝试执行的操作的正确代码是:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.date = functions.https.onRequest((request, response) => {
    response.send("Hello, Functions");
})

可能会产生这样的错误,

XMLHttpRequest cannot load https://us-central1-idntt-baed5.cloudfunctions.net/date. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://idntt-baed5.firebaseapp.com' is therefore not allowed access. The response had HTTP status code 500.

请在 xhr 请求

中使用此标头
req.setRequestHeader('Access-Control-Allow-Origin', '*');  

尝试在mozilla firefox中运行,由于安全问题,Google Chrome不支持此功能

答案 2 :(得分:0)

如果您通过firebase中托管的站点/页面请求该功能,则您(firebase hosting)应添加重写规则。 Firebase文档中对此进行了解释:https://firebase.google.com/docs/hosting/functions#directing_hosting_requests_to_your_function