index.js//后端
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")
('sk_test_51IvTMySJHm59a7wpdl1wmkkj3uAIYN4XEBKuZO0ezF3vKR2dubLbzOEDLjCug
6wtULBK2mUsPWjJLol0NfMw67A000kWGNbvkb'); //Security code provide via stripe
//API
// - App config
const app = express();
// - Middlewares
app.use(cors({ origin: true }));
app.use(express.json());
// - API routes
app.get('/', (req, res) => {
res.status(200).send('hello world');
})
app.post("/payments/create", async (req, res) => {
const total = req.query.total;
console.log('Payment has been received !!! for this amount >>> ', total);
const paymentIntent = await stripe.paymentIntents.create({
amount: total, //This is in sub units
currency: "usd",
});
res.status(201).send({
clientSecret: paymentIntent.client_secret,
})
})
// - Listen Command
exports.api = functions.https.onRequest(app);
付款js//前端Raect组件
import { CardElement, useElements, useStripe } from '@stripe/react-stripe-js';
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import CurrencyFormat from 'react-currency-format';
import { Link, useHistory } from 'react-router-dom';
import CheckoutProduct from './CheckoutProduct';
import './Payment.css';
import { getBasketTotal } from './reducer';
import { useStateValue } from './StateProvider';
function Payment() {
const [{ user, basket }, dispatch] = useStateValue();
const stripe = useStripe();
const elements = useElements();
const history = useHistory();
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true)
const [succeeded, setSucceeded] = useState(false)
const [processing, setProcessing] = useState('')
const [clientSecret, setClientSecret] = useState(true)
useEffect(() => {
//generate the special stripe secret which allows us to charge a customer
const getClientSecret = async () => {
const responce = await axios({
method: 'post',
// Stripe expects the subunit of whatever currency you are using
url: `/payments/create?total=${getBasketTotal(basket) * 100}`
});
setClientSecret(responce.data.clientSecret);
}
getClientSecret();
}, [basket])
console.log('The Secret is >>>', clientSecret);
const handleSubmit = async e => {
e.preventDefault();
setProcessing(true);
const payload = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement)
}
}).then(({ paymentIntent }) => {
//paymentIntent = payment confirmation
setSucceeded(true);
setError(null);
setProcessing(false);
history.replace('/orders');
})
}
const handleChange = e => {
setDisabled(e.empty);
setDisabled(e.error ? e.error.message : '')
}
return (
<div className='payment'>
<div className="paymentContainer">
<h1>
Checkout (<Link to='/checkout'>{basket.length} items</Link>)
</h1>
<div className="paymentSection">
<div className="paymentTitle">
<h3>Delivery Address</h3>
</div>
<div className="paymentAddress">
<p>{user?.email}</p>
<p>Om nagar</p>
<p>Jayraj Building, Vasai</p>
</div>
</div>
<div className="paymentSection">
<div className="paymentTitle">
<h3>Review items and delivery</h3>
</div>
<div className="paymentItems">
{basket.map(item => (
<CheckoutProduct
id={item.id}
title={item.title}
price={item.price}
rating={item.rating}
img={item.img} />
))}
</div>
</div>
<div className="paymentSection">
<div className="paymentTitle">
<h3>Payment Method</h3>
</div>
<div className="paymentDetails">
<form onSubmit={handleSubmit}>
<CardElement onChange={handleChange} />
<div className="paymentPriceContainer">
<CurrencyFormat
renderText={(value) => (
<>
<h3>Order Total : {value}</h3>
</>
)}
decimalScale={2}
value={getBasketTotal(basket)}
displayType={"text"}
thousandSeparator={true}
prefix={"$"}
/>
<button disabled={processing || disabled || succeeded}>
<span>{processing ? <p>Processing</p> : 'Buy Now'}</span>
</button>
</div>
{error && <div>{error}</div>}
</form>
</div>
</div>
</div>
</div>
)
}
export default Payment
axios.js
import axios from 'axios';
const instance = axios.create({
baseURL='http://localhost:5001/app-eea29/us-central1/api' //baseurl from firebase emulator suite
})
export default instance;
xhr。js:177个职位http://localhost:3000/payments/create?total=4534404(未找到)
未捕获(promise)错误:请求失败,状态代码404在createError(createError.js:16)在结算(settle.js:17)在XMLHttpRequest.handle加载(xhr.js:62)
看起来您缺少axios中的“数据”属性。
我附上了代码。试试看它是否有效。
import instance from './path-to-axios'; <------- IMPORTANT
useEffect(() => {
//generate the special stripe secret which allows us to charge a customer
const getClientSecret = async () => {
const responce = await instance({
method: 'post',
// Stripe expects the subunit of whatever currency you are using
url: `/payments/create`,
data: getBasketTotal(basket) * 100
});
setClientSecret(responce.data.clientSecret);
}
getClientSecret();
}, [basket])
编辑:(因为提供了第一个答案)
记住使用您创建的实例,而不是axios本身。
您将实例导出为具有基本URL的axios实例,但在react组件中,您没有使用它-您使用的是axios({…}),其中没有基本URL。我觉得这就是你的问题所在
嗨,我正在通过axios尝试reactjs POST请求,但出现错误,我查看了所有文档,但错误未得到解决。 这是我的错误: 未捕获(promise中)错误:请求在XMLHttpRequest的结算(eval at(bundle.js:4621),:15:15)处的createError(eval at(bundle.js:4615),:18:12)处失败,状态代码为400。手工装载(在(捆js:4
我使用HttpURLConnection通过POST向服务器发送数据。我设置标头,然后获取输出流并写入一些字节,然后关闭输出流。 我试图从给定的网址获取时间表细节的下一页。但是有些我怎么也得不到结果。请帮助任何人,如果你知道这个代码中的任何问题。 我看到的是有错误的第一页,而不是第二页。"您选择的电台组合无效。请致电LIRR旅游信息中心,电话号码是(718) 217-5477,向客服代表咨询更多信
我正在编写一个控制器来处理来自AJAX的帖子。我一直收到一个错误,那篇文章不受支持。我以前在尝试创建后控制器方法时从未遇到过以下错误,我希望有人能发现我在哪里搞砸了。 这是我为控制控制器中的帖子而编写的方法: 使用JQuery 1.10,这是请求它的Ajax调用: 我知道POST地址是正确的,因为将它转换成GET请求就可以了。此外,我还编写了其他POST请求,它们在同一个控制器类中也能正常工作。任
login.jsp 用户列表.jsp AppController.java 有2页:login.jsp-起始页,其中包括与登录和密码填充的形式-userlist.jsp结果列表“显示数据库中所有用户持久化”..首先显示登录页面,当我单击提交按钮时,我得到了这个错误:org . spring framework . web . servlet . pagenotfound-不支持请求方法“POST”
下面是我的方法 当调用GET request时,它的工作很好,但是当我们调用POST request和request payload checkout_token=xxxx时,我得到以下错误 编辑 甚至我尝试删除所有参数,但仍然没有运气到目前为止。
我刚刚开始学习Java Spring Boot for REST API开发。在下面的代码中,GET方法可以正常工作,但POST不能。 在Postman应用程序中使用as 错误 在日志中我可以看到, maven的Java和springboot版本,