Heroku部署GPT应用后请求返回200但无预期响应(返回HTML)的问题排查求助
Heroku部署GPT应用后请求返回200但无预期响应(返回HTML)的问题排查求助
我最近开发了一个小型GPT聊天应用,本地运行时一切正常,但部署到Heroku后出现了奇怪的问题:前端发送POST请求到/api/chat时,网络状态码显示200,但返回的不是预期的JSON响应,而是index.html文件。有没有大佬能帮忙分析下可能的问题?以下是我的代码:
server.js
const express = require('express'); const fetch = require('node-fetch'); const path = require('path'); const app = express(); app.use(express.json()); app.use(express.static(path.join(__dirname, 'build'))); app.post('/api/chat', async (req, res) => { console.log('Request body:', req.body); try { const response = await fetch( 'https://api.openai.com/v1/chat/completions', { method: "POST", headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.REACT_APP_API_KEY}` }, body: JSON.stringify(req.body) } ); if (!response.ok) { throw new Error (`OpenAI API responded with status ${response.status}`); } const data = await response.json(); console.log('Response:', data); res.json(data); } catch (error) { console.error('Error handling /api/chat request:', error); res.status(500).json({error: 'Internal Server Error'}); } }); app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); app.listen(process.env.PORT || 8080);
chatgpt.js
import { useState, useEffect} from 'react'; const ChatGpt = () => { const [message, setMessage] = useState([]); const [newUserMessage, setNewUserMessage] = useState({ role: 'user', content: 'Hello' }); const [input, setInput] = useState(''); const handleInputChange = (e) => { setInput(e.target.value); }; useEffect(() => { const fetchResponse = async () => { try { const response = await fetch( '/api/chat', { method: "POST", headers: { 'Content-Type': 'application/json', }, body: JSON.stringify( { model: 'gpt-3.5-turbo', messages: [{role: 'system', content: ''}, {role: 'user', content: newUserMessage.content}], max_tokens: 600, }), }, ); const data = await response.json(); console.log(data); const botResponse = data.choices[0].message.content; setMessage(prevMessages => [...prevMessages, {role: 'chat GPT', content: botResponse}]); } catch (error) { console.log('Error sending message:', error); } }; if(newUserMessage) { setMessage(prevMessages => [...prevMessages, newUserMessage]); setNewUserMessage(null); fetchResponse(); } }, [newUserMessage]); const handleSubmit = async (e) => { e.preventDefault(); if (input.trim() !== '') { setNewUserMessage({role: 'user', content: input}); setInput(''); } }; return ( <div className='chatbot' style={ChatbotStyles.chatbot}> <div className='chatbox' style={ChatbotStyles.chatbox}> <div className='messages' style={ChatbotStyles.messages}> {message.map((message, index) => ( <div key={index} className='message' style={ChatbotStyles.message}> {message.role === 'system' ? ( <div className='bot-message' style={ChatbotStyles.botMessage}>{message.content}</div> ) : ( <div className='user-message'>{message.content}</div> )} </div> ))} </div> <form style={ChatbotStyles.chatbox} onSubmit={handleSubmit}> <input type="text" value={input} onChange={handleInputChange} placeholder='How can I help you?' style={ChatbotStyles.input} /> <button style={ChatbotStyles.button} onClick={handleSubmit}>Submit Prompt</button> </form> </div> </div> ); }; const ChatbotStyles = { chatbot: { width: '500px', height: '500px', backgroundColor: '#f0f0f0', border: '1px solid #ccc', borderRadius: '5px', margin: '0 auto', padding: '1px 7px 10px 5px', }, chatbox: { display: 'flex', flexDirection: 'column', padding: '10px', }, messages: { maxHeight: '300px', overflowY: 'scroll', }, message: { marginBottom: '10px', }, botMessage: { backgroundColor: '#007bff', color: 'white', padding: '5px 10px', borderRadius: '5px', marginLeft: 'auto', }, input: { maxWidth: '100%', padding: '8px', border: '1px solid #ccc', borderRadius: '5px', marginBottom: '5px', height: '30px' }, '&:focus': { outline: 'none' }, button: { backgroundColor: 'blue', color: 'white', border: 'none', padding: '10px 20px', borderRadius: '5px', cursor: 'pointer', }, }; export default ChatGpt;
我自己排查过的点:
- 本地开发时请求能正常命中
/api/chat路由,返回OpenAI的JSON响应 - Heroku上应用已正常部署,静态资源能正常加载
- 网络请求显示200状态,但响应内容是index.html
希望各位能帮忙指出可能的问题方向,谢谢!
备注:内容来源于stack exchange,提问作者Jolanta
相关产品推荐
相关产品推荐

