310

Expressフレームワークを使用して軌道に乗ろうとしている基本的なnode.jsアプリがあります。ファイルがあるviewsフォルダーがありindex.htmlます。しかし、Web ブラウザーのロード時に次のエラーが表示されます。

エラー: モジュール 'html' が見つかりません

以下は私のコードです。

var express = require('express');
var app = express.createServer();

app.use(express.staticProvider(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render('index.html');
});

app.listen(8080, '127.0.0.1')

ここで何が欠けていますか?

4

31 に答える 31

312

jade にプレーンな HTML ページを含めることができます。

ビュー/index.jadeで

include plain.html

views/plain.html で

<!DOCTYPE html>
...

app.js は引き続き jade をレンダリングできます。

res.render(index)
于 2012-01-19T06:49:21.877 に答える
246

これらの回答の多くは古くなっています。

Express 3.0.0 および 3.1.0 を使用すると、次のように動作します。

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

Express 3.4+ の代替構文と注意事項については、以下のコメントを参照してください。

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

次に、次のようなことができます。

app.get('/about', function (req, res)
{
    res.render('about.html');
});

viewsこれは、サブフォルダーにビューがあり、ejsノード モジュールがインストールされていることを前提としています。そうでない場合は、ノード コンソールで次のコマンドを実行します。

npm install ejs --save
于 2012-08-17T14:59:33.053 に答える
72

Express.jsガイドから:レンダリングの表示

ビューのファイル名は、の形式を取りますExpress.ENGINE。ここで、ENGINEは必要なモジュールの名前です。たとえば、ビューlayout.ejsはビューシステムに次のように指示しますrequire('ejs')。ロードされるモジュールはExpressに準拠するようにメソッドをエクスポートする必要exports.render(str, options)app.register()がありますが、エンジンをファイル拡張子にマップするために使用できるため、たとえばfoo.htmljadeでレンダリングできます。

したがって、独自の単純なレンダラーを作成するか、または単にjadeを使用します。

 app.register('.html', require('jade'));

についての詳細app.register

Express 3では、このメソッドの名前が変更されていることに注意してくださいapp.engine

于 2010-12-25T18:41:28.760 に答える
58

HTML ファイルを読み取って送信することもできます。

app.get('/', (req, res) => {
    fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
        res.send(text);
    });
});
于 2011-06-22T09:21:08.290 に答える
46

これを試して。わたしにはできる。

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

app.get('/', function(req, res){
  res.render("index.html");
});
于 2011-08-05T17:08:47.160 に答える
26
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
于 2011-11-30T14:04:15.137 に答える
20

Express@~3.0.0を使用している場合は、以下の行を例から変更してください。

app.use(express.staticProvider(__dirname + '/public'));

このようなものに:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

エクスプレスAPIページで説明されているように作成しましたが、魅力的に機能します。このセットアップを使用すると、追加のコードを記述する必要がないため、マイクロ プロダクションやテストに十分に簡単に使用できます。

以下にリストされている完全なコード:

var express = require('express');
var app = express.createServer();

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render('index.html');
});

app.listen(8080, '127.0.0.1')
于 2012-11-20T15:23:40.637 に答える
14

express 3.Xとで同じ問題に直面しましたnode 0.6.16。上記の解決策は、最新バージョンでは機能しませんexpress 3.x。メソッドを削除し、app.registerメソッドを追加しましapp.engineた。上記の解決策を試した場合、次のエラーが発生する可能性があります。

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'register'
    at Function.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:37:5)
    at Function.configure (/home/user1/ArunKumar/firstExpress/node_modules/express/lib/application.js:399:61)
    at Object.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:22:5)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

エラーメッセージを取り除くには。次の行をapp.configure function

app.engine('html', require('ejs').renderFile);

注:ejsテンプレート エンジンをインストールする必要があります。

npm install -g ejs

例:

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  app.engine('html', require('ejs').renderFile);

....

app.get('/', function(req, res){
  res.render("index.html");
});

注:最も簡単な解決策は、ejs テンプレートをビュー エンジンとして使用することです。そこでは、生の HTML を *.ejs ビュー ファイルに書き込むことができます。

于 2012-06-29T06:17:53.050 に答える
9

viewsディレクトリを使用する必要がない場合は、html ファイルを以下のpublicディレクトリに移動するだけです。

次に、この行を「/views」の代わりに app.configure に追加します。

server.use(express.static(__dirname + '/public'));
于 2012-10-04T16:14:55.157 に答える
7

ノードで Html ページをレンダリングするには、以下を試してください。

app.set('views', __dirname + '/views');

app.engine('html', require('ejs').renderFile);
  • 次のようにしてejsモジュールをインストールする必要があります。npm

       npm install ejs --save
    
于 2016-07-05T06:07:59.830 に答える
6

私のプロジェクトでは、次の構造を作成しました。

index.js
css/
    reset.css
html/
    index.html

このコードは、リクエストに対して index.html を提供し、/リクエストに対して reset.css を提供し/css/reset.cssます。十分に単純で、最良の部分は、キャッシュ ヘッダーが自動的に追加されることです。

var express = require('express'),
    server = express();

server.configure(function () {
    server.use('/css', express.static(__dirname + '/css'));
    server.use(express.static(__dirname + '/html'));
});

server.listen(1337);
于 2012-05-30T20:55:35.027 に答える
4

Express 4.0.0 では、app.js の 2 行をコメントアウトするだけです。

/* app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); */ //or whatever the templating engine is.

次に、静的ファイルを /public ディレクトリにドロップします。例: /public/index.html

于 2014-04-17T17:44:19.157 に答える
3

Express ルートで res.sendFile() 関数を試してください。

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

app.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

app.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

app.listen(3000);

console.log("Running at Port 3000");

ここを読む: http://codeforgeek.com/2015/01/render-html-file-expressjs/

于 2015-01-20T04:24:39.693 に答える
3

HTML ファイルを配信するだけで ejs に依存したくなかったので、小さなレンダラーを自分で作成しました。

const Promise = require( "bluebird" );
const fs      = Promise.promisifyAll( require( "fs" ) );

app.set( "view engine", "html" );
app.engine( ".html", ( filename, request, done ) => {
    fs.readFileAsync( filename, "utf-8" )
        .then( html => done( null, html ) )
        .catch( done );
} );
于 2016-06-03T14:42:42.283 に答える
3

2行以下に追加しましたが、うまくいきます

    app.set('view engine', 'html');
    app.engine('html', require('ejs').renderFile);
于 2014-10-15T12:40:57.153 に答える
2

1) 最善の方法は、静的フォルダーを設定することです。メイン ファイル (app.js | server.js | ???) で:

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

public/css/form.html
public/css/style.css

次に、「パブリック」フォルダーから静的ファイルを取得しました。

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

ファイルキャッシュを作成できます。
メソッド fs.readFileSync を使用する

var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');

app.get('/', function(req, res){    
    res.setHeader('Content-Type', 'text/html');
    res.send( cache["index.html"] );                                
};);
于 2014-02-27T09:45:32.520 に答える
2

これは Express サーバーの完全なファイルのデモです!

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

それがあなたのために役立つことを願っています!

// simple express server for HTML pages!
// ES6 style

const express = require('express');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const app = express();

let cache = [];// Array is OK!
cache[0] = fs.readFileSync( __dirname + '/index.html');
cache[1] = fs.readFileSync( __dirname + '/views/testview.html');

app.get('/', (req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.send( cache[0] );
});

app.get('/test', (req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.send( cache[1] );
});

app.listen(port, () => {
    console.log(`
        Server is running at http://${hostname}:${port}/ 
        Server hostname ${hostname} is listening on port ${port}!
    `);
});

于 2016-11-28T12:08:07.857 に答える
2

エクスプレス RESTful API を使用して角度のあるアプリをセットアップしようとしていて、このページに何度もアクセスしましたが、役に立ちませんでした。これが私が見つけたものです:

app.configure(function() {
    app.use(express.static(__dirname + '/public'));         // set the static files location
    app.use(express.logger('dev'));                         // log every request to the console
    app.use(express.bodyParser());                          // pull information from html in POST
    app.use(express.methodOverride());                      // simulate DELETE and PUT
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});

次に、API ルートのコールバックは次のようになります。res.jsonp(users);

クライアント側のフレームワークはルーティングを処理できます。Express は API を提供するためのものです。

私のホームルートは次のようになります。

app.get('/*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
于 2014-03-05T22:37:17.787 に答える
2

次の行をコードに追加します

  1. package.json ファイルの「jade」を「ejs」に、「XYZ」(バージョン) を「*」に置き換えます。

      "dependencies": {
       "ejs": "*"
      }
    
  2. 次に、app.js ファイルに次のコードを追加します。

    app.engine('html', require('ejs').renderFile);

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

  3. ビューフォルダーにすべての.HTMLファイルを保持することを忘れないでください

乾杯 :)

于 2016-02-06T17:39:41.320 に答える
2
res.sendFile(__dirname + '/public/login.html');
于 2015-02-27T10:07:32.403 に答える
0

server.js にインクルードしてください

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});
于 2015-10-27T05:22:09.273 に答える
-1

普段はこれを使っています

app.configure(function() {
    app.use(express.static(__dirname + '/web'));
});

/web ディレクトリ内のすべてのものを共有するため、注意してください。

役立つことを願っています

于 2012-11-25T04:15:43.750 に答える
-2

node.js にエクスプレス フレームワークを使用している場合

npm ejs をインストールする

次に、構成ファイルを追加します

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router)

;

エクスポート モジュール form.js からページをレンダリングします form.html.ejs

次にform.jsを作成します

res.render('form.html.ejs');

于 2013-08-28T11:38:46.597 に答える