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:
Directory Structure:
public_html/
server.mjs
index.html
node_modules
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
<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.
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.
Could someone please help me identify the problem and suggest a solution to make the API endpoint accessible within my cPanel-hosted application?
Thank you!
2
Answers
Try following my steps to fix your error
.mjs
extension, make sure to enable "ESM" inpackage.json
.path
forserver.mjs
andstatic
middlewareAPI
path, that’s wrong usage.refs
https://expressjs.com/en/guide/routing.html
https://expressjs.com/en/starter/static-files.html
The first argument should be the local path, not an absolute URL.
That should be
app.get('/chat',
with similar changes for all your other routes.Your server side code should not be exposed to the public.
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.
The use of a public_html directory is quite common for shared hosting using Apache.
I’ve never seen it for a Node.js application.
Make sure the hosting serving you are using actually supports Node.js applications and that you are deploying it correctly.