gpt4 book ai didi

node.js - 处理单页应用程序 url 路由

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:51 25 4
gpt4 key购买 nike

我想让所有请求返回index.html页面,其中包含将处理其自己的路由的前端应用程序。我还希望 css/html/images/js 能够正确返回,这样就不会为所有这些返回 index.html 。所以我在 server.js 中有类似的东西

var express = require('express');
var app = express();
var path = require("path");


app.use(express.static(path.join(__dirname,"app")));
app.get('*', function(req, res) {
console.log(res);
res.sendFile(path.join(__dirname, 'app', 'index.html')); // load the single view file (angular will handle the page changes on the front-end)
});


app.listen(5000);

现在,如果我输入 localhost:5000 我可以获得所有资源,一切都很好。但是,如果我创建 localhost:5000/something 我猜想 express.static 找不到的每个资源都是由 app.get(*,. ..) 因此所有资源都以 index.html 形式返回。

那么我怎样才能让这种设置起作用呢?!

最佳答案

这是正确的做法。阅读评论。

var staticUrl = '/static';
var publicFolder = path.resolve(__dirname, '../public')//make sure you reference the right path

//serve all atatic files prefixed with '/static/*'
app.use(staticUrl, express.static(publicFolder));
app.use(staticUrl, function(req, res, next) {
res.send(404);
});

//serve index.html for all not 'static' prefixed requests
app.all('/*', function(req, res) {
res.sendfile('index.html', {root: publicFolder});
});

关于node.js - 处理单页应用程序 url 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25907554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com