[英]why my front end(react) and back-end(express) is not connecting
我的前端和后端没有连接。 它的 show xhr.js:184 POST http://localhost:3000/payments/create?total=12999 404 (Not Found)错误。 有关更多信息,我在下面提供了必要的代码。
这是我的后端(快递)的 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 文件,我想在其中使用来自后端的数据,当人们点击支付按钮而不是个人 clientSecret 更改为真实 ID 时。
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 是我的反应服务器...
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}`
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.