如何解决在同一端口条带集成上基于React前端和Node Express构建的应用程序?
我已经在前端使用React创建了一个现有的在线商店应用,并且我正在尝试使用后端的NODE Express将STRIPE集成为付款方式。我想在同一端口上启动它们,并尝试在package.json中使用代理,并通过将index.html作为静态文件提供服务,但是它不起作用。
我确实将index.html用作静态文件,但除html之外似乎没有读取任何其他内容。 这是我的代码:
server.js
const express = require('express');
require('dotenv').config('.env');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const path = require('path')
import Products from './src/components/Products';
import CartItem from './src/components/context/cartProvider';
const app = express();
// I am trying to serve the whole React app as static file
app.use(express.static('public'));
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname,'public','index.html'))
})
// ENDPOINTS FOR SESSION HERE
app.post("/create-checkout-session",async (req,res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],line_items: [
// Here we have to send clonedCart[] as body
],mode: "payment",success_url: "https://example.com/success",cancel_url: "https://example.com/cancel",});
res.json({ id: session.id });
});
app.listen(4000,() => console.log('Server is running on port 4000'))
在package.json中,我添加了以下行:
"proxy": "http://localhost:4000",
值得称React在默认端口3000上执行
解决方法
无法从node.js服务器代码提供静态html。由于您仅使用公用文件夹html,因此无法使用它。要使用它,您需要使用构建版本。
从您的问题中我可以理解的是,您可能需要在同一个端口上运行它们,因为可能会出现cors错误。因此,请使用cors模块。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。