提问者:小点点

建立在React(前端)和Node Express在同一端口(条纹集成)上的App?


我有一个现有的在线商店应用程序在前端创建了React和我正在尝试整合STRIPE作为支付方法使用NODE express在后端。我希望在同一个端口上启动它们,我尝试使用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",

在默认端口3000上执行React的值


共1个答案

匿名用户

从node.js服务器代码提供静态html将不起作用。由于您使用的只是公用文件夹html,因此无法使用。要使用它,您需要使用构建版本。

从你的问题中我能理解的是,你需要在同一个端口上运行它们,因为你可能会得到cors错误。所以使用cors模块。