javascript - React Fetch Google Cloud Function http cors req.method OPTIONS, POST
问题描述
节省时间并跳过回答
我的 axios 'GET'this.props.profile.id
从 正确登录到控制台有什么问题react-redux-firebase
,但这是另一回事。
...
const response = await axios.get(
"https://us-central1-thumbprint-1c31n.cloudfunctions.net/listCharts",
{ 'seatsioid': this.props.profile.id }
);
还是云功能标题?
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 中间件: https ://expressjs.com/en/resources/middleware/cors.html
cors 中间件的谷歌云函数抽象:https ://cloud.google.com/functions/docs/writing/http
通过 http 调用 GCFunctions(用于获取): https ://firebase.google.com/docs/functions/http-events
反应获取(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,谢谢
推荐阅读
- c# - 为什么你不能运行一个任务并用另一种方法捕获它
- sql - 在sql中转换时间
- c++ - 如何分别在R和C++中做两个矩阵的矩阵乘积
- sql - rexp_like - 似乎无法理解它是如何工作的
- javascript - 与服务器的连接不断失败连接 ETIMEDOUT 94.195.191.104:27017
- python - tensorflow 如何使用 tf.map_fn 批量处理 (?, 40,30,128) 和 (?,40,30) 的两个输入张量形状,?是我的批量大小
- isabelle - 我可以使用类和语言环境以代数方式构造一个 while 结构吗?
- php - 在 VB 中加密的 PHP 中的解密
- sql-server - 为什么 DATEDIFF 返回 -1
- python - 我们如何使用弹性搜索在 django rest 框架中获得热门搜索列表?