質問

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')

ここで何が足りないのでしょうか?

役に立ちましたか?

解決

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

ビュー/index.jade

include plain.html

ビュー/slain.html

<!DOCTYPE html>
...

そして、app.jsはまだJadeをレンダリングすることができます:

res.render(index)

他のヒント

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

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

Express.jsガイドから: レンダリングを表示します

ファイル名を見るフォームを取得します Express.ENGINE, 、 どこ ENGINE 必要になるモジュールの名前です。 たとえば、ビュー layout.ejs View Systemに伝えます require('ejs'), 、ロードされているモジュール メソッドをエクスポートする必要があります exports.render(str, options) ただし、Expressに準拠するために app.register() エンジンをマッピングして拡張機能をファイルするために使用できます。たとえば foo.html ジェイドによってレンダリングできます。

したがって、独自のシンプルなレンダラーを作成するか、Jadeを使用するだけです。

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

もっとapp.register.

Express 3では、この方法が変更されたことに注意してください app.engine

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

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");
});

HTMLファイルを読んで送信することもできます。

app.get('/', (req, res) => {
    fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
        res.send(text);
    });
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});

使用している場合 特急@~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')

私も同じ問題に直面しました express 3.Xnode 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テンプレートをビューエンジンとして使用することです。そこでは、 *.ejsビューファイルにraw HTMLを記述できます。

使用する必要がない場合 ビュー ディレクトリは、HTMLファイルをに移動するだけです 公衆 以下のディレクトリ。

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

server.use(express.static(__dirname + '/public'));

フォルダー構造:

.
├── index.html
├── node_modules
│   ├──{...}
└── server.js

server.js

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

app.use(express.static('./'));

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

app.listen(8882, '127.0.0.1')

index.html

<!DOCTYPE html>
<html>
<body>

<div> hello world </div>

</body>
</html>

出力:

こんにちは世界

ノードでHTMLページをレンダリングするには、次のことを試してください。

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

app.engine('html', require('ejs').renderFile);
  • インストールする必要があります ejs モジュールを通して npm お気に入り:

       npm install ejs --save
    

私のプロジェクトのために、私はこの構造を作成しました:

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);

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

私は2行以下に追加しました、それは私のために働きます

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

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/

単に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 );
} );

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

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

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

次に、「public」フォルダーから静的ファイルを取得しました。

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"] );                                
};);

Express Restful APIを備えたAngularアプリをセットアップしようとしていて、役に立たなかったものの、このページに何度も着陸しようとしていました。これが私が見つけたものです。

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)
});
res.sendFile(__dirname + '/public/login.html');

これが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}!
    `);
});

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

  1. 「Jade」を「EJS」と「XYZ」(バージョン)に置き換えます。

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

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

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

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

乾杯 :)

以前はstaticsミドルウェアで処理されていた高速ルートで「/」のリクエストを処理することを許可したかったのです。これにより、index.htmlの通常のバージョンまたは、アプリケーションの設定に応じて、連結 +模倣JSおよびCSSを読み込んだバージョンをレンダリングすることができます。に触発された アンドリュー・ホーミーの答え, 、HTMLファイル(変更されていない)をビューフォルダーにドラッグすることにしました。

   app.engine('html', swig.renderFile);
   app.set('view engine', 'html');
   app.set('views', __dirname + '/views');  

そして、そのようなルートハンドラーを作成しました

 app.route('/')
        .get(function(req, res){
            if(config.useConcatendatedFiles){
                return res.render('index-dist');
            }
            res.render('index');       
        });

これはかなりうまくいきました。

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.
});

すでにすべてのコンテンツを持っているHTMLファイルを提供しようとしている場合、「レンダリング」する必要はありません。「提供する必要があります」。レンダリングとは、ページがブラウザに送信される前にサーバーの更新または挿入コンテンツがある場合、他の回答が示すように、EJのような追加の依存関係が必要です。

ブラウザをリクエストに基づいてファイルに向けたい場合は、使用する必要があります res.sendfile() このような:

const express = require('express');
const app = express();
var port = process.env.PORT || 3000; //Whichever port you want to run on
app.use(express.static('./folder_with_html')); //This ensures local references to cs and js files work

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/folder_with_html/index.html');
});

app.listen(port, () => console.log("lifted app; listening on port " + port));

これにより、Express以外に追加の依存関係は必要ありません。サーバーに既に作成されたHTMLファイルを送信したい場合は、上記は非常に軽量な方法です。

プレーンHTMLの場合、NPMパッケージやミドルウェアは必要ありません

これを使用するだけです:

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

index.js

var Express = require( 'Express'); var app = express(); app.use(express.static(__ dirname + '/public'));

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


app.listen(3400, () => {
    console.log('Server is running at port 3400');
})

index.htmlファイルをパブリックフォルダーに配置します

<!DOCTYPE html>
<html>
<head>
    <title>Render index html file</title>
</head>
<body>
    <h1> I am from public/index.html </h1>
</body>
</html>

次に、端末で次のコードを実行します

ノードindex.js

私は通常これを使用します

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

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

私はそれが役立つことを願っています

Express Frameworkを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からページをレンダリングします。jsは、ejsファイル名の拡張機能を備えたビュー監督にhtmlファイルを持っています。form.html.ejs

次に、form.jsを作成します

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top