如何使用 node.js 处理客户端路由?
How to handle client side routing with node.js?
在node/express,我有这个
var express = require('express');
var path = require('path');
// start express module
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/*
* Visit the home page
*/
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('My site started at http://%s:%s', host, port);
});
因此我只能使用主页 link 或直接指向服务器上的某个文件才能访问我的页面。
但是在客户端,我使用具有历史 API 的单页应用程序设计,并且有一个类似于 localhost:3000/work
的路由。因此,如果我要转到根页面,有一个按钮使用历史记录 api 将 url 更改为 /work
,它最终会显示新内容。
但是,如果我手动访问 localhost:3000/work
,node.js 认为我需要找到一个名为 localhost:3000/work/index.html
或其他名称的文件,并说找不到页面。我如何设置它以便页面请求仍然触发 index.html
的 return?
谢谢
抱歉没有写评论(我还不能)。
不熟悉您的客户端路由设置(可以分享吗?)。
这不是最佳做法,只是为了确保您的客户端设置正常 - 您能否检查一下它是否正常工作:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('*', function (req, res) {
res.redirect('/');
});
在node/express,我有这个
var express = require('express');
var path = require('path');
// start express module
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
/*
* Visit the home page
*/
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('My site started at http://%s:%s', host, port);
});
因此我只能使用主页 link 或直接指向服务器上的某个文件才能访问我的页面。
但是在客户端,我使用具有历史 API 的单页应用程序设计,并且有一个类似于 localhost:3000/work
的路由。因此,如果我要转到根页面,有一个按钮使用历史记录 api 将 url 更改为 /work
,它最终会显示新内容。
但是,如果我手动访问 localhost:3000/work
,node.js 认为我需要找到一个名为 localhost:3000/work/index.html
或其他名称的文件,并说找不到页面。我如何设置它以便页面请求仍然触发 index.html
的 return?
谢谢
抱歉没有写评论(我还不能)。
不熟悉您的客户端路由设置(可以分享吗?)。
这不是最佳做法,只是为了确保您的客户端设置正常 - 您能否检查一下它是否正常工作:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('*', function (req, res) {
res.redirect('/');
});