仅在浏览器上调用自己的Firbase函数被CORS阻止

问题描述 投票:1回答:2

我收到错误:

Access to XMLHttpRequest at 'https://us-central1-myproject-64732.cloudfunctions.net/getProduct has been blocked by CORS

我的域注册为example.com

编辑

我有:

      const cors = require('cors')({origin: true});
      const rp = require('request-promise');

      exports.getProduct = functions.https.onRequest((request, response) => {    
        const options = {
        uri: url,
        headers: {

        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': '*',
        'Accept-Language': 'en-US,en',
        "Access-Control-Allow-Origin":"*",
        'Access-Control-Allow-Methods': 'GET, PUT, POST, OPTIONS',
        'Access-Control-Allow-Headers': '*',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Referer': 'http://www.google.com/',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
      }
          rp(options)
          .then(($) => { ...

我的Access-Control-Allow-Origin在那儿,但错误提示未出现。

EDIT2

此功能在本地计算机以及终端模拟器中使用时均有效,但在浏览器中不起作用。

node.js firebase
2个回答
1
投票

尝试这样:

import * as functions_ from 'firebase-functions';
// import * as firebaseHelper from 'firebase-functions-helper';
import * as express_ from 'express';
import * as bodyParser_ from "body-parser";
import News from './news.function';
import Meteo from './meteo.function';

const _cors = require('cors')({
    origin: true,
});

let bodyParser = bodyParser_;
let express = express_;
let functions = functions_;
// const db = admin.firestore();
const app = express();
const main = express();




// YOUR API ROUTES  
app.get('/news/', (req, res) => News(req, res));
app.get('/meteo/', async (req, res) => {
    console.log('here');
    Meteo(req, res)
});

main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));




// webApi is your functions name, and you will pass main as 
// a parameter
export const webApi = functions.https.onRequest((req, resp) => {
    _cors(req, resp, () => {
        main(req, resp);
    })
});

希望对您有帮助!


0
投票

对任何挣扎的人,我找到了解决方案。

exports.getProduct = functions.https.onRequest((request, response) => {

     cors(request, response, () => { // ******  thats solve it

       const options = {
        uri: url,
        headers: { ......

         rp(options)
          .then(($) => { ...

添加cors请求使其生效。包括图书馆。我还发现,当我部署单个功能时-它不会总是部署它,否则会产生一些奇怪的问题。

© www.soinside.com 2019 - 2024. All rights reserved.