为什么我的前端(react)和后端(express)没有连接



我的前端和后端没有连接。其显示xhr.js:184POSThttp://localhost:3000/payments/create?total=12999404(未找到(错误。有关更多信息,我在下面提供了必要的代码。

这是我的后端(express(的index.js文件

const functions = require('firebase-functions');
const express = require('express')
const cors = require('cors')
const stripe="   "
const app=express()
app.use(cors({origin:true}))
app.use(express.json())
app.get('/',(req,res)=>{
res.status(200).send('hello world')
})
app.post('/payments/create',async(req,res)=>{
//   console.log("api is working")

const total=req.query.total
console.log('payment req recievd is',total)

const paymentIntent = await stripe.paymentIntent.create({
amount:total,
currency:"usd"
})
res.status(201).send({

clientSecrat:paymentIntent.client_secret
})
})
exports.api=functions.https.onRequest(app)

这是我的axios.js文件

import axios from 'axios'
const instance=axios.create({
baseURL:'http://localhost:5001/challange-c1266/us-central1/api' 
}
)
export default instance

这是我的payment.js文件,当人们点击支付按钮时,我想使用后台的数据

const [clientSecret, setClientSecret] = useState(true)
useEffect(() => {
console.log("use effect is working")
const getClientSecret = async () => {
console.log("get client sec is is working")
const response = await axios({
method: 'post',
url: `/payments/create?total=${getBasketTotal(basket) * 100}`
})
// console.log('response is >>>>>>>>>>>',response)
// console.log(response.data)
setClientSecret(response.data.clientSecret)
}
getClientSecret()
}, [basket])
console.log('the secrate is >>>>>>>>', clientSecret)

但当我点击付款按钮时,我在控制台中出现错误,如下所示localhost:3000是我的react服务器。。。

xhr.js:184 POST http://localhost:3000/payments/create?total=12999 404 (Not Found)createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:69)

React代码正在上运行

http://localhost:3000

当您通过axios进行API调用时,它将使用相同的端口进行API调用您必须在API调用中传递端口5001

const response = await axios({
method: 'post',
url: `localhost:5001/payments/create?total=${getBasketTotal(basket) * 100}`
})

今后,您可以使用通用的baseURL使API调用

BaseUrl = window.location.protocol + '//' + window.location.hostname + ":5001/";

并使用

const response = await axios({
method: 'post',
url: `${BaseUrl}payments/create?total=${getBasketTotal(basket) * 100}`
})

最新更新