如何使用express快速提供相同的文件?

Zan*_*cox 6 node.js express angularjs

有什么办法可以随时提供相同的文件吗?

因此,如果他们访问website.com/ajsdflkasjd,它仍然提供与website.com/asdnw相同的文件

我想使用express with node来做这件事.

我有的文件是静态html文件,而不是玉文件.

顺便说一句,我想要这样做的原因,如果你想知道,我有一个angularjs应用程序,为我处理所有路由.所以,我需要做的只是提供一页,它会照顾其余的.

提前致谢!

Zan*_*cox 12

新的答案

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)
Run Code Online (Sandbox Code Playgroud)

老答案

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)
Run Code Online (Sandbox Code Playgroud)