Encountering frontend routing issues in my Node.js SPA: AJAX calls work when starting from the homepage, but entering URLs directly returns raw JSON. How can this be resolved?
// clientSideCode.js
function fetchContent(routeSegment) {
$.ajax({
method: 'GET',
url: '/data/' + routeSegment,
dataType: 'json',
success: function(response) {
$('#displayArea').html(response.info);
}
});
}
// serverSideCode.js
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/data/:type', (req, res) => {
// Mimics fetching product details
res.json({ info: 'Example product information' });
});
app.get('*', (req, res) => {
res.sendFile(__dirname + '/public/home.html');
});
app.listen(3000);