我正在使用 React Native 作为项目的前端,并使用 redux 工具包将数据解析到后端。我还在后端使用外部 API,并且后端与外部 API 的通信运行良好。但是,当我尝试在前端调用该函数时,它返回网络请求失败。有人可以帮我找出代码中哪里出错了吗?
这是前端 APISlice 的片段
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
const baseUrl = 'http://localhost:8080/'
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl }),
endpoints: (builder) => ({
// Payments
createTopupIntent: builder.mutation({
query: (data) => ({
url: 'topup/intents',
method: 'POST',
body: data,
})
})
})
})
export const {
useCreateTopupIntentMutation,
} = apiSlice
import { configureStore } from '@reduxjs/toolkit';
import { apiSlice } from './apiSlice';
export const topup = configureStore({
reducer: {
api: apiSlice.reducer,
},
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
});
这就是前端实际调用该函数的地方。
import { useCreateTopupIntentMutation } from '../../store/apiSlice'
const total = navigation.getId("amount")
const [createTopupIntent] = useCreateTopupIntentMutation()
const onCheckout = async () => {
// 1. Create a payment intent
const response = await createTopupIntent({
amount: Math.floor(total * 1000),
})
console.log(response)
这是我的后端index.js 中的路由。
const express = require('express')
const topupRoutes = require('./src/router/topupRoutes')
const bodyParser = require('body-parser')
const app = express()
const PORT = 8080
app.use(bodyParser.json())
app.use('/topup', topupRoutes)
app.get('/', (req, res) => {
res.send('<h2>Hello World</h2>')
})
app.listen(PORT, "0.0.0.0", () => {
console.log('API is listening on PORT', PORT)
})
这是路由端点规范片段。
const express = require('express')
const router = express.Router()
const stripe = require('stripe')(
'STRIPE_SECRET_KEY'
)
// ALL ROUTER ENDPOINTS
router.post('/intents', async(req, res) => {
try {
// CREATE TOP UP INTENT
const topupIntent = await stripe.paymentIntents.create({
amount: req.body.amount, // INTEGER
currency: 'usd',
automatic_payment_methods: {
enabled: true
}
})
// RETURN THE SECRET
res.json({topupIntent: topupIntent.client_secret})
} catch (e) {
res.status(400).json({
error: e.message,
})
}
})
module.exports = router
我通过将 localhost 更改为我当前连接的本地 IP 地址解决了该问题。