【发布时间】:2020-09-20 18:33:17
【问题描述】:
发生了一些非常奇怪的事情。 我正在使用 Cloud Functions 构建 API。基本上,云函数向服务器发出请求并检索令牌。
这是代码
exports.Klarna = functions.https.onRequest((req, res) => {
// const app = express();
// app.use(cors({ origin: true }));
res.set('Access-Control-Allow-Origin', '*');
const url = "https://someLink.com";
const creds = req.body;
const token = `Basic ${Buffer.from(
`${"Pxxx"}:${"xxx"}`
).toString("base64")}`;
request(
"https://somelink.com",
{
method: "POST",
url: url,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: token,
},
Authorization: token,
body: creds,
json: true,
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(response.body.client_token);
}
}
);
});
然后我使用 redux-thunk 和 axios 从前端(reactJS)调用它:
export function Klarna() {
return async (dispatch) => {
try {
let response = await axios('https://google.cloud.function', {
method: 'POST',
redirect: 'follow',
headers: { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*",Authorization: "Basic XXX" },
body: JSON.stringify({
"purchase_country": "SE",
"purchase_currency": "SEK",
"locale": "sv-SE",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [
{
"type": "physical",
"reference": "19-402",
"name": "Battery Power Pack",
"quantity": 1,
"unit_price": 10,
"tax_rate": 0,
"total_amount": 10,
"total_discount_amount": 0,
"total_tax_amount": 0
}
]
}),
json: true
})
console.log(response);
} finally {
console.log("yea!")
}
}
}
然而,当邮递员成功时,我得到了
[Error] Failed to load resource: The request timed out. (Klarna, line 0)
[Error] Unhandled Promise Rejection: Error: timeout of 0ms exceeded
(anonymous function) (main.chunk.js:7307)
asyncFunctionResume
(anonymous function)
promiseReactionJobWithoutPromise
promiseReactionJob
有什么建议可以帮助我继续前进吗?这个错误已经解决了 2 天,但我没有找到解决方法。
更新:
我四处走走,找到了怎么做。代码如下:
const functions = require("firebase-functions");
const express = require("express");
var rp = require("request-promise");
const cors = require("cors")({
origin: true,
allowedHeaders: [
"Access-Control-Allow-Origin",
"Access-Control-Allow-Methods",
"Content-Type",
"Origin",
"X-Requested-With",
"Accept",
"Authorization"
],
methods: ["POST", "OPTIONS"],
credentials: true,
});
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.json");
var request = require("request");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
exports.Klarnas = 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://yourLink.com",
"http://localhost:3000",
"http://localhost:5001/xxx/xxx",
];
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}
const url = "https://someLink.com";
const creds = req.body;
const token = `Basic ${Buffer.from(
`${"XXXX"}:${"XXX"}`
).toString("base64")}`;
request(
"https://someLink.com",
{
method: "POST",
url: url,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: token,
},
Authorization: token,
body: creds,
json: true,
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(response.body.client_token);
}
}
);
}
} else {
//Origin Bad!!
//SEND or end
return res.status(400).send("no access for this origin");
}
});
});
【问题讨论】:
-
您似乎发布了敏感/私人信息。请重置您的密码和/或撤销 API 密钥和令牌,因为它们在互联网上发布时被视为已泄露。如果发布了个人身份信息,请edit 删除信息,然后标记您的帖子以供版主编辑修订。
标签: node.js reactjs axios google-cloud-functions