gpt4 book ai didi

node.js - 设置与 Express 服务器的 react

转载 作者:太空宇宙 更新时间:2023-11-03 22:20:30 25 4
gpt4 key购买 nike

所以我尝试将 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"));


我有一个处理 Stripe 付款的 Checkout.js 文件。它将生成的 token 发送到 Express 服务器。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 并尝试 post 操作后,我收到 405 不允许错误。我已尝试添加 CORS,如上面的服务器文件中所示,但它不起作用。

最佳答案

你是否尝试添加cors中间件来表达喜欢

app.use(cors())

关于node.js - 设置与 Express 服务器的 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com