【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource - React, Express请求的资源上没有“Access-Control-Allow-Origin”标头 - React、Express
【发布时间】:2021-02-23 23:45:16
【问题描述】:

我正在开发一个使用 firebase 云函数和 express.js 作为后端的简单反应电子商务应用程序。在尝试获取客户端密码时,我收到了如下所示的 COR 错误:

    Access to XMLHttpRequest at 'http://localhost:5001/challenge-3e08a/us-central1/api/payments/create?23900' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Payment.js:31 Customer error logged >>>  Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

我这样设置云功能: 用于云功能的 index.js

    const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors"); //({ origin: true });
const stripe = require("stripe")(
  "sk_test_51HlmzWCtn9NABLoH_________0Xp9jXQ0g"
);

// - API

// - App Config
const app = express();

// - Middlewares
app.use(cors({
  origin : true
}));

app.use(express.json());

// - API routes
app.get("/", (request, response) => response.status(200).send("Hello World"));

app.post(
  "/payments/create",
  async (request, response) => {
    const total = request.query.total;

    console.log("Payment request received BOOM!!! for this amount --- ", total);

    const paymentIntent = await stripe.paymentIntent.create({
      amount: total, // sub-units of the currency
      currency: "usd",
    });

    // OK
    response.status(201).send({
      clientSecret: paymentIntent.client_secret,
    });

    response.json({ msg: "This is CORS-enabled for an allowed domain." });
  }
);

app.listen(5001, function () {
  console.log("CORS-enabled web server listening on port 5001");
});

// - Listen command
exports.api = functions.https.onRequest(app);

下面是支付组件的一部分,它使获取请求在身份验证后从条带中获取客户端密码。客户端密码将用于授权电子商务应用程序上的付款。请注意:所有必要的导入都已完成,因此未将它们包含在此处,以免问题过长。

    import { getBasketTotal } from "./reducer";
    import axios from "./axios";

    function Payment() {
    const [{ basket, user }, dispatch] = useStateValue();
    const history = useHistory();

    const stripe = useStripe();
    const elements = useElements();

    const [succeeded, setSucceeded] = useState(false);
    const [processing, setProcessing] = useState("");
    const [error, setError] = useState(null);
    const [disabled, setDisabled] = useState(true);
    const [clientSecret, setClientSecret] = useState("");

    useEffect(() => {
        // generate the secpail stripe secret which allows us to charge a customer
        getClientSecret();
    }, [basket]);

    const getClientSecret = async () => {
        const response = await axios({
        method: "post",
        // currency total in sub-units
        url: `/payments/create?total=${getBasketTotal(basket) * 100}`,
        })
        .then((response) => console.log(response.data.clientSecret))
        .catch((error) => console.log("Customer error logged >>> ", error));

        setClientSecret(response.data.clientSecret);

        console.log("THE CLIENT SECRET IS >>> ", clientSecret);
    };

感谢我能得到的每一个帮助,因为这是我的第一个 react 项目。

【问题讨论】:

  • 在您的客户发布请求中,您没有在正文中发送任何数据。 POST 请求不应该将数据放入正文中吗?看来您可能正在查询字符串中发送数据。可能不是问题的根源,但使用 POST 请求似乎是一种奇怪的方式。

标签: reactjs express axios stripe-payments


【解决方案1】:

差不多就是这样:https://stackoverflow.com/a/18643011/379538

您的前端和后端在不同的端口上运行,但您并未在 CORS 设置中明确允许这样做。

如果您使用的是create-react-app,则应该考虑使用代理:https://create-react-app.dev/docs/proxying-api-requests-in-development/

【讨论】:

    猜你喜欢
    • 2019-01-13
    • 2017-02-07
    • 2023-03-16
    • 2014-07-30
    • 2016-01-14
    • 2023-03-15
    • 2018-12-02
    • 2015-10-30
    • 2019-10-07
    相关资源
    最近更新 更多