【问题标题】:Setting up react with express server设置与快递服务器的反应
【发布时间】:2019-10-21 09:41:27
【问题描述】:

所以我尝试将 Stripe 集成到 React 中,它需要设置一个 node js express 服务器。 服务器设置良好,并通过我对package.json 和我编写的新server.js 文件所做的一些更改部署到 Heroku 时返回 react 的构建文件夹。

// package.json

{
...

"scripts": {
    "dev": "react-scripts start",
    "start": "node server.js",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "heroku-postbuild": "yarn run build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "proxy": "http://localhost:9000",
  "engines": {
    "node": "10.15"
  }
}

// server.js

const express = require("express");
const app = express();
const path = require("path")
const cors = require("cors")


app.use(express.static(path.join(__dirname, 'build')));
app.use('/charge', express.json());
// app.use(cors())

let whitelist = ['localhost:9000', 'http://myapp.herokuapp.com', 'http://herokuapp.com']
let corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
            callback(null, true)
        } else {
            callback(new Error('Not allowed by CORS'))
        }
    }
}

app.post("/charge", cors(corsOptions), async (req, res) => {
    try {
        let {amount, tokenId, stripe_key, company_name} = req.body; // params sent in with client
        const stripe = require("stripe")(stripe_key); // initializes stripe with the stripe keys passed from client
        // console.log(amount, tokenId, stripe_key);
        let description = `Payment for posting for ${company_name} on MyApp.io`
        let {status} = await stripe.charges.create({
            amount,
            currency: "usd",
            description,
            receipt_email: 'emeruchecole9@gmail.com',
            source: tokenId
        });
        console.log(status);
        res.json({status});
    } catch (error) {
        // res.status(500).end();
        res.json({error}).end();
        console.log(error)
    }
});

app.get('*', (req,res) =>{
    res.sendFile(path.join(__dirname+'/build/index.html'));
});


app.listen(process.env.PORT || 9000, () => console.log("Listening on port 9000"));


我有一个处理条纹支付的Checkout.js 文件。它将生成的令牌发送到快递服务器。 Checkout.js文件中发送POST数据到服务器的部分是:

axios({
                  method: 'post',
                  url: '/charge',
                  headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                  },
                  data: {
                    amount: amount*100 || 2000, //this should be dynamic and coming from price of selected tier in tier selection plan
                    tokenId,
                    stripe_key,
                    company_name: company_name || 'Test Inc.'
                  }
            })

问题是这样的: 这完全适用于dev 模式(当我运行yarn run dev 然后node server.js 启动服务器时)以及当我运行yarn run build 手动构建和yarn run start 启动服务器并为构建提供服务时根据上面的 server.js 文件创建文件。 但是在部署到 heroku 并尝试发布操作后,我得到了一个405 Not Allowed Error。我已经尝试添加 CORS,如上面的服务器文件中所示,但它不起作用。

【问题讨论】:

  • 你是在客户端(当你调用你的服务器时)还是在你的服务器中(当你调用stripe.charges.create
  • 我认为客户端没有问题。所有客户端代码(包括 Stripe 标记化)都有效。但是当它到达 axios 代码块以将创建的令牌发送到服务器时,我的 chrome 浏览器会记录错误。
  • @Cole,当您将应用程序部署到 Heroku 时,您的应用程序是否在 https 后面提供服务?我会这样假设,因为 Heroku 应该使用 TSL 托管它的应用程序。说在您的 CORS 设置中,您将“'myapp.herokuapp.com'”列入白名单,这可能应该是 'https://myapp.herokuapp.com',您可以尝试让我知道吗

标签: node.js reactjs express stripe-payments


【解决方案1】:

你有没有尝试添加cors中间件来表达 喜欢

app.use(cors())

【讨论】:

    【解决方案2】:

    只需在 server.js 的第一个添加下面的代码

    app.use(function(req, res, next) {
    

    res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 下一个(); });

    我希望这段代码对你有帮助,对我有帮助。

    您也可以阅读这篇文章: clickme:)

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2020-01-12
      • 2014-07-03
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多