javascript - React Fetch Google Cloud Function http cors req.method 选项,POST

标签 javascript reactjs firebase cors google-cloud-functions

save time and skip to answer

我的 axios 'GET' this.props.profile.idreact-redux-firebase 正确登录到控制台有什么问题,但那是另一回事了。

...

const response = await axios.get(
  "https://us-central1-thumbprint-1c31n.cloudfunctions.net/listCharts",
  { 'seatsioid': this.props.profile.id }
);

还是云函数 header ?

const functions = require('firebase-functions');
//const admin = require('firebase-admin');
const { SeatsioClient } = require('seatsio')
const cors = require('cors')
//admin.initializeApp(functions.config().firebase);


// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.listCharts = functions.https.onRequest(async(req, res) => {
  cors(req, res, async () => {
    res.set('Access-Control-Allow-Origin', 'https://1c31n.csb.app');
    //res.set('Access-Control-Allow-Credentials', 'true');

    res.set('Access-Control-Allow-Methods', 'GET');
    res.set('Access-Control-Allow-Headers', 'Content-Type', 'X-Requested-Width', 'Accept', 'seatsioid')
    res.set('Access-Control-Max-Age', '60');
  var allowedOrigins = ['https://1c31n.csb.app', 'https://1c31n.codesandbox.io'];
  var origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){}
  const seatsioid = **req.get('seatsioid')
  let clientAdmin = new SeatsioClient('<THIS_IS_MY_ADMIN_SEATSIO_secretKey>')
  let subaccountInfo = await clientAdmin.subaccounts.retrieve(seatsioid);
  let secretKey = subaccountInfo.secretKey
  let clientDesignerKey = subaccountInfo.designerKey
  let charts = []
  let clientUser = new SeatsioClient(secretKey)
  for await(let chart of clientUser.charts.listAll()){
    charts.push(`chart":"${chart.key}`)
    }
    let couple = {
      charts,
      clientDesignerKey
    }
    res.send(couple)
})
})

谢谢

最佳答案

这对我来说花了几天时间。希望这对读者有所帮助

express' cors middleware : https://expressjs.com/en/resources/middleware/cors.html

Google Cloud Function abstraction for cors middleware : https://cloud.google.com/functions/docs/writing/http

Call GCFunctions thru http (for fetch) : https://firebase.google.com/docs/functions/http-events

react 获取(URL,{})

async componentDidMount() {
    //console.log(this.props.profile)
    //this.setState({ posterOptions: this.props.profile.pages.unshift('post as myself')})
    //const seatsioid = this.props.profile.id;
    await fetch(
      "https://us-central1-foldername.cloudfunctions.net/function",
      {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "Application/JSON",
          "Access-Control-Request-Method": "POST"
        },
        body: JSON.stringify({ seatsioid: this.props.profile.id }),
        maxAge: 3600
        //"mode": "cors",
      }
    )
      .then(response => response.json())
      .then(body => {
        console.log(body);
        //const reader = response.body.getReader()
        //reader.read().then(value => {
        //console.log(value);
        this.setState({
          allCharts: body.couple[0].charts,
          secretKey: body.couple[0].secretKey
        });
      })
      .catch(err => console.log(err));
}

谷歌云函数

const functions = require("firebase-functions");
const { SeatsioClient } = require("seatsio");
const cors = require("cors")({
  origin: true,
  allowedHeaders: [
    "Access-Control-Allow-Origin",
    "Access-Control-Allow-Methods",
    "Content-Type",
    "Origin",
    "X-Requested-With",
    "Accept"
  ],
  methods: ["POST", "OPTIONS"],
  credentials: true
});

exports.listCharts = functions.https.onRequest((req, res) => {
  // Google Cloud Function res.methods
  res.set("Access-Control-Allow-Headers", "Content-Type");
  res.set("Content-Type", "Application/JSON");
  // CORS-enabled req.methods, res.methods
  return cors(req, res, async () => {
    res.set("Content-Type", "Application/JSON");
    var origin = req.get("Origin");
    var allowedOrigins = [
      "https://www.yoursite.blah",
      "https://yoursite2.blah"
    ];
    if (allowedOrigins.indexOf(origin) > -1) {
      // Origin Allowed!!
      res.set("Access-Control-Allow-Origin", origin);
      if (req.method === "OPTIONS") {
        // Method accepted for next request
        res.set("Access-Control-Allow-Methods", "POST");
        //SEND or end
        return res.status(200).send({});
      } else {
          // After req.method === 'OPTIONS' set ["Access-Control-Allow-Methods": "POST"]
          // req.method === 'POST' with req.body.{name} => res.body.{name}
          // req.method === 'PUT' with req.body.{name}, no res.body.{name}
        let couple = [];
        if (req.body.seatsioid) {
          const seatsioid = req.body.seatsioid;
          let clientAdmin = new SeatsioClient("YOUR_ADMIN_KEY");
          let subaccountInfo = await clientAdmin.subaccounts.retrieve(seatsioid);
          let secretKey = subaccountInfo.secretKey;
          let charts = [];
          let clientUser = new SeatsioClient(secretKey);
          for await (let chart of clientUser.charts.listAll()) {
            charts.push(`chart":"${chart.key}`);
          }
          couple = [
            {
              charts: charts,
              secretKey: secretKey
            }
          ];
          //SEND or end
          res.status(200).send({ couple });
        } else {
          //SEND or end
          res.status(400).send("No seatsioid defined!");
        }
      }
    } else {
      //Origin Bad!!
      //SEND or end
      return res.status(400).send("no access for this origin");
    }
  });
});

有 1500 个代表点数的人应该为他们的其他用户添加 seatio 标签来替换 reactjs 或 javascript,谢谢

关于javascript - React Fetch Google Cloud Function http cors req.method 选项,POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817987/

相关文章:

javascript - Redux-form 调用外部表单组件提交

javascript - 如何在 jest/enzyme 测试中测试 axios get 请求函数?

javascript - 在 html 中嵌入 google 演示文稿 + 单击 JS 中的下一张幻灯片

reactjs - JEST - 如何使用同一 __test__ 文件夹中的实用程序管理不同的测试文件

javascript - Firebase v3.1 Web SDK - Github oAuth 不起作用

ios - iOS 应用程序的 Firebase 3.7.0 上的链接错误

javascript - Firebase/JS - 在加载页面之前触发 JavaScript?

javascript - 没有 PHP 的 iframe 应用程序的 Facebook reveal-tab/like-gate(请使用 Rails 或 javascript)

javascript - 如何在复选框内显示数组元素 - ionic

javascript - 后台 Javascript 或 Cordova 应用程序中的计时器任务梯级