我已经在注释代码中尝试了代码(注释和未注释),它显示错误reply.file不是一个功能。在未注释的代码中,它显示错误未知的处理程序文件 我还包括惰性。
server.route({ // Other assets If you have
method: 'GET',
path: '/public/js/{filename}',
handler: {
file: function (request) {
return './public/js/'+request.params.filename;
}
// try{
// console.log(request.params);
// reply.file( './public/js/'+request.params.filename);
// }
// catch(e){
// console.log(e);
// reply.file( './public/js/'+request.params.filename);
// }
}
});
答案 0 :(得分:2)
提供静态文件需要inert模块
'use strict';
const Hapi = require('hapi');
const Inert = require('inert');
const server = new Hapi.Server();
// config
server.connection({
port: 3000
});
// register routes
server.register(Inert, (err) => {
if (err) {
throw err;
}
// default html
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file('./public/index.html');
}
});
// default /js directory
server.route({
method: 'GET',
path: '/js/{params*}',
handler: {
directory: {
path: './public/js',
listing: false
}
}
});
});
// run
server.start(() => {
console.log('Server running at:', server.info.uri);
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Hapi demo: serving static files</title>
<script type="text/javascript" src="js/foo.js"></script>
</head>
<body>
<h2>see console output.</h2>
</body>
</html>
'use strict';
(function () {
console.log('foo.js has been loaded');
})();
请参阅:http://hapijs.com/tutorials/serving-files#relative-paths
答案 1 :(得分:1)
见:http://hapijs.com/tutorials/serving-files#relative-paths 使用inert模块
server.register(Inert, function () {
server.route( {
method: 'GET',
path: '/{param*}',
handler: {
directory: { path: Path.normalize(__dirname + '/') }
}
});
您也可以尝试
server.register(Inert, () =>{
server.route( {
method: 'GET',
path: '/public/js/{filename}',
handler: {
file: function (request) {
return __dirname+'/public/js/'+request.params.filename;
}
}
});
});