Node.js + Express最简单的SPA示例

时间:2017-10-24 08:21:45

标签: javascript node.js express single-page-application

我正在尝试制作一个小型SPA应用程序。

我的app文件夹中有以下结构:

/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>

当我转到http://localhost:3000/static/时,它会显示我的主页。但是当我点击about链接时,它会在http://localhost:3000/static/about

上抛出404

如何解决此问题?我希望将其作为SPA(因此在浏览页面时不刷新)。

谢谢!

1 个答案:

答案 0 :(得分:3)

这不是SPA,您有多个静态网页,而且您基本上是将所有请求发送到index页面,不允许用户转到任何其他静态网页,例如about

您需要研究SPA及其工作原理,因为这不是它们的配置方式。您可以使用JavaScript框架(React,Angular等)在客户端或服务器端使用路由匹配来执行此操作。

相关问题