简体   繁体   中英

Node.js + Express simplest SPA example

I'm trying to make a tiny SPA app work.

I have a following structure in my app folder:

/about.html
/index.html
/index.js

index.js:

const express = require('express');
const app = express();
const path = require('path');

const staticHref = '/static';
const publicFolder = path.join(__dirname, '/');

app.use(staticHref, express.static(publicFolder));
app.use(staticHref, function(req, res) {
    res.send(404);
});

app.all('/*', function(req, res) {
    res.sendFile('index.html', {root: publicFolder});
});

app.listen(3000, function(){
    console.log('running');
});

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Homepage</title>
</head>
<body>
<h1>Homepage</h1>
<a href="/static/about">About</a>
</body>
</html>

about.html:

<!DOCTYPE html>
<html>
<head>
    <title>About Us</title>
</head>
<body>
<h1>About Us</h1>
<a href="/static">Home</a>
</body>
</html>

When I go to http://localhost:3000/static/ it shows my homepage. But when I click the about link it throws 404 on http://localhost:3000/static/about

How can I resolve this issue? I want to work it as SPA (so no refresh while navigating through the pages).

Thanks!

This is not an SPA, you have multiple static pages and you're basically sending all your requests to your index page not allowing users to go to any of your other static pages like about .

You need to research SPAs and how they work because that's not how they are configured. You can use a JavaScript framework (React, Angular etc.) to do this, either on the client-side or on the server-side with route matching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM