server.js
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../front-end/index.html'));
})
app.get('/api/users', (req, res) => {
const users = [{
id: '123',
name: 'Shaun',
}, {
id: '234',
name: 'Bob',
}, {
id: '345',
name: 'Sarah',
}];
res.json(users);
})
app.listen(8080, () => {
console.log('server is listening on port 8080');
});
main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
fetch('/api/users')
.then(res => res.text())
.then(users => console.log(users));
ReactDOM.createRoot(document.getElementById('root')).render(
<div>test</div>
)
index.html
<!doctype html>
<html lang="en">
<head></head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
file structure
(https://i.sstatic.net/F0TRfNqV.png)
Expected result: console log in the browser of the user array from server.js when loading localhost:8080
Actual result: console log of index.html
Sorry if this is a noob question — I am new to web development and have scoured google search and stackoverflow for a couple days for an explanation for why this occurs but couldn’t find a definitive answer. Any help is appreciated. Thanks!
Checked the file path, file structures, package.json files, vite.config.js file, netstat on port 8080
Anan Ma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.