快递:是否有可能简化res.sendFile中的path?
这是我的目录结构:
/用户/蒂蒂/ myproject的/应用/服务器/
…. app.js
…./上市
…….. / CSS
…….. / JS
……../视图
…………的index.html
………… about.html
和我的app.js文件:
var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/', function (req, res) { res.sendFile('/Users/Titi/myproject/app/server/public/view/index.html'); }); app.get('/about', function (req, res) { res.sendFile('/Users/Titi/myproject/app/server/public/view/about.html'); }); app.listen(2000, function () { console.log('Example app listening on port 2000!'); });
它完美的作品。
但是我想知道是否有办法不必编写整个path(/Users/Titi/myproject/app/server/public/view/about.html)。
可以简化吗?
你可以在sendFile()
选项中指定一个root
path:
var viewOpts = { root: '/Users/Titi/myproject/app/server/public/view' }; app.get('/', function (req, res) { res.sendFile('index.html', viewOpts); });
或者您可以使用内置path为您创build绝对path:
var path = require('path'); // Assuming this script is inside the `server` portion of the path app.get('/', function (req, res) { res.sendFile(path.resolve('public/view/index.html')); });
你可以创build一个variables并存储那个path。
const tmpldir = '/Users/Titi/myproject/app/server/public; app.get('/', function (req, res) { res.sendFile(`${tmpldir}/index.html`); });
注意:理想情况下,你应该使用router
而不是app
;
设置视图文件夹和查看引擎安装ejs模板npm install ejs
但您需要更改sendFile
app.set('views', '/Users/Titi/myproject/app/server/public/view'); app.set('view engine', 'html'); app.engine('.html', require('ejs').renderFile); app.get('/', function (req, res) { res.render('index'); });
如果你仍然想使用sendFile
你需要指定绝对path