我如何始终使用Express提供相同的文件? [英] How do I always serve the same file with express?
问题描述
有什么办法可以始终提供相同的文件吗?
Is there any way I can always serve the same file?
因此,如果他们转到website.com/ajsdflkasjd,则该文件仍与website.com/asdnw提供相同的文件
So, if they go to website.com/ajsdflkasjd it still serves the same file as website.com/asdnw
我想使用带有节点的express来做到这一点.
I would like to do this using express with node.
我拥有的文件是静态html文件,而不是jade文件.
The file I have is a static html file, not a jade file.
顺便说一句,如果您想知道的话,我想要这样做的原因是我有一个angularjs应用程序,可以为我处理所有路由.因此,我所需要做的就是为该页面提供服务,其余页面将得到处理.
By the way, the reason I'm wanting to do this, in case you were wondering, is I have an angularjs app that handles all the routing for me. So, all I need to do is serve that one page, and it will take care of the rest.
提前谢谢!
推荐答案
新答案
const app= require('express')()
// static file serve
app.use(express.static(__dirname))
// not found in static files, so default to index.html
app.use((req, res) => res.sendFile(`${__dirname}/index.html`))
app.listen(3000)
旧答案
var express = require('express');
var bodyParser = require('body-parser')
var path = require('path')
var app = express();
// url encoding
app.use(bodyParser.urlencoded({extended:false}));
// gzip
// redirect all html requests to `index.html`
app.use(function (req, res, next) {
if (path.extname(req.path).length > 0) {
// normal static file request
next();
}
else {
// should force return `index.html` for angular.js
req.url = '/index.html';
next();
}
});
// static file serve
app.use(express.static(__dirname))
app.listen(3000)
这篇关于我如何始终使用Express提供相同的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!