Node.js 在同一端口上基于React(前端)和Node Express构建的应用程序(条带集成)?
我有一个现有的在线商店应用程序创建与反应的前端,我正试图集成作为支付方式使用的后端节点表达条纹。我想在同一个端口上启动它们,我尝试使用package.json中的代理,并将index.html作为静态文件提供,但它不起作用 我确实将index.html作为静态文件提供,但它似乎不读取除html之外的任何内容。 这是我的密码: server.jsNode.js 在同一端口上基于React(前端)和Node Express构建的应用程序(条带集成)?,node.js,reactjs,express,stripe-payments,Node.js,Reactjs,Express,Stripe Payments,我有一个现有的在线商店应用程序创建与反应的前端,我正试图集成作为支付方式使用的后端节点表达条纹。我想在同一个端口上启动它们,我尝试使用package.json中的代理,并将index.html作为静态文件提供,但它不起作用 我确实将index.html作为静态文件提供,但它似乎不读取除html之外的任何内容。 这是我的密码: server.js const express = require('express'); require('dotenv').config('.env'); const
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模块。您不需要在此处使用代理。从您的评论中,我猜您的React捆绑包没有在您托管的index.html文件中被引用。单页React应用程序基本上可以归结为一个index.html文件,其中包含应用程序的JavaScript包,该包通常使用Webpack编写。我建议您查看index.html文件并确保它包含您的应用程序包。提供静态文件的方式似乎也有点不合适。通常你只需要一行代码:
app.use('/',express.static(path.join(uu dirname,'public',index.html'))代码>。