Easypost Node.js 示例难点?

Easypost Node.js Example Difficulties?

我目前正在尝试实施 Easypost API 但是文档中的示例是在我的前端 (localhost:3000) 上控制台记录 null...有谁知道我在做什么错误的?谢谢...第一次使用 firebase 以及 easypost 和 react

functions/index.js:

const functions = require("firebase-functions");
const EasyPost = require("@easypost/api");

const api = new EasyPost(TEST_API_KEYS);

exports.buyShipping = functions.https.onCall((data, res) => {
  const shipment = new api.Shipment({
    from_address: {
      street1: "417 MONTGOMERY ST",
      street2: "FLOOR 5",
      city: "SAN FRANCISCO",
      state: "CA",
      zip: "94104",
      country: "US",
      company: "EasyPost",
      phone: "415-123-4567",
    },
    to_address: {
      name: "Dr. Steve Brule",
      street1: "179 N Harbor Dr",
      city: "Redondo Beach",
      state: "CA",
      zip: "90277",
      country: "US",
      phone: "4155559999",
    },
    parcel: {
      length: 8,
      width: 5,
      height: 5,
      weight: 5,
    },
  });

  shipment.save().then((s) => {
    s.buy(shipment.lowestRate()).then((result) => {
      return result;
    });
  });

  });
});

前端:

import { initializeApp } from "firebase/app";
import { getFunctions, httpsCallable } from 'firebase/functions';

///

const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);
const buyShipping = httpsCallable(functions, 'buyShipping')

const buy = async () => {              
       await buyShipping().then((result) => {
          /** @type {any} */
          console.log(result)
    })} 

///

<button onClick={buy}>Purchase</button>

看起来您正在后台登录控制台,这不会做任何有用的事情。相反,您需要 return 从后端调用 buyShipping 的结果,这样您的前端就可以将其显示在页面或控制台上,记录它或您打算对其进行的任何操作。此外,您的两个函数调用不共享相同的名称,因此您实际上不太可能调用您的后端(基于提供的示例)。 buyShipping 是后端函数的名称,但您在前端调用 sendPackage

您会希望所有逻辑都存在于您的后端节点服务器上,除了 return 之外什么都不做。然后,通过从后端调用这些函数,您所有的“表示”逻辑(显示、日志记录等)都将在前端发生。

我发现了问题;我的 firebase 后端的 shipment.save 函数中不能有 return...这有效:

exports.buyShipping = functions.https.onCall((data, res) => {
  const shipment = new api.Shipment({
    from_address: {
      street1: "417 MONTGOMERY ST",
      street2: "FLOOR 5",
      city: "SAN FRANCISCO",
      state: "CA",
      zip: "94104",
      country: "US",
      company: "EasyPost",
      phone: "415-123-4567",
    },
    to_address: {
      name: "Dr. Steve Brule",
      street1: "179 N Harbor Dr",
      city: "Redondo Beach",
      state: "CA",
      zip: "90277",
      country: "US",
      phone: "4155559999",
    },
    parcel: {
      length: 8,
      width: 5,
      height: 5,
      weight: 5,
    },
  });

  const arrayData = shipment.save().then((s) => {
    return s;
  });
  return arrayData;
});