【发布时间】:2023-02-12 23:19:29
【问题描述】:
我正在 JS 中试验 ChatGPT API。我的预构建应用程序在本地运行良好。但是,当我构建应用程序并将其上传到运行 Apache2 的 Ubuntu VPS 时,出现以下错误:
Uncaught (in promise) SyntaxError: Unexpected token <, <!doctype "... is not valid JSON
错误控制台指向我的 App.js 文件,特别是这一行:
.then((data) => setResponse(data.message));
我花了几个小时试图找到解决方案。 Apache 中的配置看起来不错,.htaccess 也一样。我不知道为什么输出被解析为 HTML 而不是 JSON。
Chrome 控制台中的网络选项卡返回状态 200,但未给出任何输出。
应用程序.js
import React, { useState } from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:3001/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ message }),
})
.then((res) => res.json())
.then((data) => setResponse(data.message));
};
return (
<div className="App">
<h1>Destiny</h1><br></br><br></br>
<form onSubmit={handleSubmit}>
<textarea
value={message}
placeholder="Chat with Destiny A.I."
onChange={(e) => setMessage(e.target.value)}
></textarea> <br></br><br></br>
<button type="submit">Submit</button>
</form> <br></br><br></br>
{response && <div class="div-1">{response}</div> }
</div>
);
}
export default App
索引.JS
const OpenAI = require('openai');
const { Configuration, OpenAIApi } = OpenAI;
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3001;
const configuration = new Configuration({
organization: "org-Jf1SIWc0RkT7Nf7f7V2Gkr23",
apiKey: "sk-xx",
});
const openai = new OpenAIApi(configuration);
app.use(bodyParser.json());
app.use(cors());
app.post('/', async (req, res) => {
const { message } = req.body;
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: `
${message}?`,
max_tokens: 120,
temperature: 0,
});
console.log(response.data)
if(response.data.choices[0].text){
res.json({message: response.data.choices[0].text})
}
});
app.listen(port, () => {
console.log('err.response.data');
});
【问题讨论】:
-
您可以尝试将
.then((res) => res.json())更改为.then((res) => res.text()),然后使用.then(html => console.log(html))登录以查看您正在使用的 HTML 文档是什么。也可能值得记录响应状态。 -
请修剪您的代码,以便更容易找到您的问题。按照这些指南创建一个minimal reproducible example。
-
我很抱歉没有回复。它出于某种原因服务的文件是 index.html。 React 应用程序可以完美地预构建。目前还没有找到解决这个问题的方法。
-
您部署的应用程序在发出请求时是否仍在尝试点击
localhost:3001? -
目前没有官方的 ChatGPT API。请阐明“ChatGPT API”的含义。
标签: javascript node.js reactjs express openapi