44

Node.js を長い間使用しておらず、express を使用したこともありません。アプリケーションを起動すると、次のように返されました。

Error: Cannot find module 'html'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at new View (C:\Users\fr\node_modules\express\lib\view.js:42:49)
  at Function.app.render (C:\Users\fr\node_modules\express\lib\application.js:483:12)
  at ServerResponse.res.render (C:\Users\fr\node_modules\express\lib\response.js:755:7)
  at allClients (C:\Users\fr\node_modules\apps\chat.js:13:7)
  at callbacks (C:\Users\fr\node_modules\express\lib\router\index.js:161:37)
  at param (C:\Users\fr\node_modules\express\lib\router\index.js:135:11)

test.html を起動したときにエラーが発生しました。コードは次のとおりです。

var io = require('socket.io');
var express = require('express');

var app = express(),
http = require('http'),
server = http.createServer(app),
socket = require('socket.io').listen(server);

app.configure(function(){
    app.use(express.static(__dirname));
});
app.get('/', function(req, res, next){
    res.render('./test.html');
});

server.listen(8333);

私の進路 :

node_modules/
    express/
    socket.io/
    apps/
        chat.js
        test.html

なんで ?

編集 :

これは私の新しい app.configure です:

app.configure(function(){
    app.use(express.static(path.join(__dirname, 'public')));
});

しかし、それは戻ります:

 path is not defined
4

6 に答える 6

68

test.html は静的ファイルであると想定しています。静的ファイルをレンダリングするには、静的ミドルウェアを使用します。

app.use(express.static(path.join(__dirname, 'public')));

これにより、Express はアプリケーションの public ディレクトリで静的ファイルを探すように指示されます。

これを指定したら、ブラウザでファイルの場所を指定するだけで、ファイルが表示されます。

ただし、ビューをレンダリングする場合は、適切なレンダラーを使用する必要があります。レンダリングのリストは consolidate で定義されてます。使用するライブラリを決定したら、インストールするだけです。私は口ひげを使用しているので、ここに私のスニペットがあります設定ファイル

var engines = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

これが何をするかは、

  • ビューディレクトリでレンダリングするファイルを探します

  • mustache を使用してファイルをレンダリングする

  • ファイルの拡張子は .html です (.mustache も使用できます)。

于 2013-04-19T18:42:53.263 に答える
29

簡単な方法は、EJS テンプレート エンジンを使用して .html ファイルを提供することです。ビューエンジンのセットアップのすぐ隣に次の行を追加します。

app.engine('html', require('ejs').renderFile);
于 2014-06-10T12:26:13.010 に答える
2

ビューエンジンを宣言する必要があるかもしれません。

ビュー/テンプレート エンジンを使用する場合:

app.set('view engine', 'ejs');

また

app.set('view engine', 'jade');

ただし、プレーン html をレンダリングするには、次の投稿を参照してください:基本的な HTML ビューをレンダリングしますか? .

于 2013-04-19T18:43:38.810 に答える
2

使用する

res.sendFile()

それ以外の

res.render().

あなたがやろうとしているのは、ファイル全体を送信することです。

これは私にとってはうまくいきました。

于 2020-12-30T02:41:50.233 に答える