React Native+Expo集成ChatGPT API在Android端遇无效URL错误
问题描述
我用Expo开发集成ChatGPT API的React Native应用,Web浏览器运行正常,但通过Expo Go在Android设备上运行时出现错误:
[Error: Invalid URL (POST /v1/chat/completions/)]
Web端虽能正常工作,但存在一处无关错误。已尝试清除缓存、更换ChatGPT API模型,问题仍未解决。
以下是相关代码和package.json文件:
ChatGPT组件代码
import React, { useState } from 'react'; import { View, Text, TextInput, Button, StyleSheet, Alert } from 'react-native'; import OpenAI from "openai"; import theme from '../theme'; const ChatGPT = () => { const openai = new OpenAI({ apiKey: (here goes my api key), dangerouslyAllowBrowser: true }); const [input, setInput] = useState(''); const [messages, setMessages] = useState([]); const sendMessage = async () => { if (!input) return; // Send the user's message to the ChatGPT API try { const response = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages: [ { "role": "user", "content": input }, ], temperature: 1, max_tokens: 256, top_p: 1, frequency_penalty: 0, presence_penalty: 0, }); console.log(response); setMessages([...messages, { text: input, user: true }, { text: response.choices[0].message.content, user: false }]); setInput(''); } catch (error) { console.log(error) } }; return ( <View style={{marginTop: 40}}> <View> { //Adds the message messages.map((message, index) => ( <View style> <Text key={index} style={styles.chatContainer}> {message.text} </Text> </View> ))} </View> <View> <TextInput value={input} onChangeText={setInput} placeholder="Escriba su consulta..." /> <Button title="Send" onPress={sendMessage} /> </View> </View> ); }; const styles = StyleSheet.create({ chatContainer: { flex: 1, backgroundColor: theme.colors.backgroundPrimary, alignItems: 'center', justifyContent: 'center', color: theme.colors.textPrimary }, text: { color: "#fff" } }); export default ChatGPT;
package.json文件
{ "name": "pisapp-app", "version": "1.0.0", "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web" }, "dependencies": { "@expo/webpack-config": "^19.0.0", "@react-navigation/drawer": "^6.6.3", "@react-navigation/native": "^6.1.7", "@react-navigation/native-stack": "^6.9.13", "@react-navigation/stack": "^6.3.17", "@types/react": "~18.2.14", "axios": "^1.5.0", "dotenv": "^16.3.1", "expo": "~49.0.8", "expo-status-bar": "~1.6.0", "firebase": "^10.4.0", "openai": "^4.4.0", "react": "18.2.0", "react-dom": "18.2.0", "react-native": "0.72.4", "react-native-gesture-handler": "~2.12.0", "react-native-reanimated": "~3.3.0", "react-native-safe-area-context": "4.6.3", "react-native-screens": "~3.22.0", "react-native-web": "~0.19.6", "typescript": "^5.1.3" }, "devDependencies": { "@babel/core": "^7.20.0", "@babel/plugin-transform-export-namespace-from": "^7.22.11", "babel-eslint": "^10.1.0", "eslint-config-standard": "^17.1.0", "eslint-config-standard-jsx": "^11.0.0", "eslint-config-standard-react": "^13.0.0", "eslint-plugin-import": "^2.28.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^6.1.1", "eslint-plugin-react": "^7.33.2" }, "private": true, "eslintConfig": { "parser": "babel-eslint", "extends": [ "standard", "standard-jsx", "standard-react" ] } }
解决方案
1. 显式指定OpenAI API的baseURL
OpenAI v4版本SDK在React Native环境下,无法自动加载默认API基础地址,导致请求路径变成相对路径而非完整URL。修改OpenAI实例初始化代码,添加baseURL参数:
const openai = new OpenAI({ apiKey: "你的API密钥", dangerouslyAllowBrowser: true, baseURL: "https://api.openai.com/v1" });
2. API密钥安全提醒
dangerouslyAllowBrowser: true仅适合开发测试,生产环境绝对不能在客户端暴露API密钥,建议搭建后端代理转发请求,避免密钥泄露。
3. 额外检查点
- 确认Android设备网络正常,可访问
https://api.openai.com - 清除Expo Go缓存:在Expo Go中长按项目图标,选择"Clear Cache"后重新加载项目
Web端的无关错误可通过浏览器控制台查看具体信息,通常是React Native Web兼容性或样式问题,不影响核心功能的话可后续处理。
内容的提问来源于stack exchange,提问作者Esteban Fuentes
相关产品推荐
相关产品推荐

