gpt4 book ai didi

Getting 404 Errors when Trying to Access API Endpoint in cPanel-hosted Express.js App(尝试在cPanel托管的P2P. js应用程序中访问API端点时出现404错误)

转载 作者:bug小助手 更新时间:2023-10-25 12:40:31 26 4
gpt4 key购买 nike



I'm hosting a Node.js application on cPanel, and I'm encountering 404 errors when trying to access an API endpoint in my application. Here are the details of my setup:

我在cPanel上托管了一个Node.js应用程序,在尝试访问应用程序中的API端点时遇到了404个错误。以下是我的设置的详细信息:


Directory Structure:

目录结构:


public_html/
server.mjs
index.html
node_modules

server.mjs:

Server.mjs:


import express from 'express';
import bodyParser from 'body-parser';
import OpenAI from 'openai';
import path from 'path';

const app = express();
const port = process.env.PORT || 3000;
const apiKey = ''; // Replace with your actual OpenAI API key

const openai = new OpenAI({
apiKey: apiKey,
});

app.use(express.static(path.join(__dirname, 'public_html'))); // Serve files from public_html
app.use(bodyParser.json());

// Add a GET route for /chat
app.get('https://www.mazzn.info/chat', (req, res) => {
res.send('This is the chat page. You can use it for testing or debugging.');
});

// POST route for /chat
app.post('https://www.mazzn.info/chat', async (req, res) => {
const { msgp1 } = req.body;
let message = `Answer to this message as a doctor ${msgp1}`;

// Use OpenAI API to generate a response
try {
const completion = await openai.chat.completions.create({
messages: [{ role: 'user', content: message }],
model: 'gpt-3.5-turbo',
});

const chatbotResponse = completion.choices[0].message.content;

res.json({ chatbotResponse });
} catch (error) {
console.error('Error:', error);
// Handle the error gracefully, e.g., display an error message to the user
res.status(500).json({ error: 'An error occurred while fetching the response from the chatbot.' });
}
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

index.html

Index.html


     <div class="card">

<div class="chat-header">دردشة</div>
<div class="chat-window" id="chat-window">
<ul class="message-list" id="message-list">
<!-- Messages will be added here dynamically -->
</ul>
</div>
<div class="chat-input">
<input type="text" class="message-input" placeholder="أكتب رسالتك هنا">
<button class="send-button rounded" onclick="sendMessage()" style="background-color: #db3700;">أرسل</button>
</div>
</div>

<script>
async function sendMessage() {
var messageInput = document.querySelector('.message-input');
var messageList = document.querySelector('.message-list');
var message = messageInput.value;

if (message.trim() === '') {
return;
}

// Display user message
var userMessageContainer = document.createElement('li'); // Change from <div> to <li>
userMessageContainer.classList.add('user-message');
userMessageContainer.textContent = message;
messageList.appendChild(userMessageContainer);

messageInput.value = '';
scrollToLatestMessage();

// Send user message to the chatbot and display response
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});

if (!response.ok) {
throw new Error('API request failed with status ' + response.status);
}

const responseData = await response.json();
const chatbotResponse = responseData.chatbotResponse;

// Display chatbot response
var chatbotMessageContainer = document.createElement('li'); // Change from <div> to <li>
chatbotMessageContainer.classList.add('chatbot-message');
chatbotMessageContainer.textContent = chatbotResponse;
messageList.appendChild(chatbotMessageContainer);

// Log chatbot response to the console
console.log('Chatbot Response:', chatbotResponse);

scrollToLatestMessage();
} catch (error) {
console.error('Error:', error);
// Handle the error gracefully, e.g., display an error message to the user
alert('An error occurred while fetching the response from the chatbot.');
}
}

function scrollToLatestMessage() {
var chatWindow = document.getElementById('chat-window');
chatWindow.scrollTop = chatWindow.scrollHeight;
}
</script>

I've set up a simple chat application where users can send messages to a chatbot. The issue arises when trying to send a POST request to the /chat endpoint; I get a 404 error.

我已经设置了一个简单的聊天应用程序,用户可以向聊天机器人发送消息。在尝试向/chat端点发送POST请求时出现问题;我收到404错误。


I've confirmed that the server is running, and I've double-checked the route definitions. I suspect that the issue might be related to how cPanel handles routing and endpoints.

我已经确认服务器正在运行,并且我已经重新检查了路由定义。我怀疑这个问题可能与cPanel处理路由和端点的方式有关。


Could someone please help me identify the problem and suggest a solution to make the API endpoint accessible within my cPanel-hosted application?

有没有人可以帮我找出问题所在,并建议一个解决方案,以便在我的cPanel托管应用程序中访问API端点?


Thank you!

谢谢!


更多回答

Are you getting a 404 error when you visit https://www.mazzn.info/chat?

当您访问https://www.mazzn.info/chat?时,您是否收到了404错误

change app.get('https://www.mazzn.info/chat', to app.get('/chat',, and try it again.

将app.get(‘https://www.mazzn.info/chat’,‘更改为app.get(’/Chat‘,,然后重试。

Yeah, am getting 404 and i try both of the /chat or mazzn.info/chat. can you think with other possible thing do this problem ?

是的,我得到了404,我同时尝试了/chat或mazzn.info/chat。你能想到用其他可能的事情来做这个问题吗?

You need to add more details to your question, such as "package.json" content.

您需要在问题中添加更多细节,例如“Package.json”内容。

Try running the tree command in the project root, adding the output to the question.

尝试在项目根目录中运行tree命令,将输出添加到问题中。

优秀答案推荐


 app.get('https://www.mazzn.info/chat'


The first argument should be the local path, not an absolute URL.

第一个参数应该是本地路径,而不是绝对URL。


That should be app.get('/chat', with similar changes for all your other routes.

它应该是app.get(‘/chat’,与您的所有其他路由具有类似的更改。





public_html/
server.mjs


Your server side code should not be exposed to the public.

您的服务器端代码不应公开。



app.use(express.static(path.join(__dirname, 'public_html')));


You are looking for static files in a public_html directory that is at the same level as the server.mjs. Since server.mjs is inside that directory (which it shouldn't be, as I mentioned above) you won't find them.

您要在与server.mjs相同级别的public_html目录中查找静态文件。因为server.mjs在该目录中(正如我上面提到的,它不应该在目录中),所以您不会找到它们。




The use of a public_html directory is quite common for shared hosting using Apache.

对于使用Apache的共享主机来说,使用public_html目录是非常常见的。


I've never seen it for a Node.js application.

我从来没有在Node.js应用程序中看到过它。


Make sure the hosting serving you are using actually supports Node.js applications and that you are deploying it correctly.

确保您正在使用的托管服务实际支持Node.js应用程序,并且您正确地部署了它。


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com