2017-11-14 1 views
0

私はserver.useで立ち往生していますが、node.jsです。私がserver.use(express.static('public'));server.getの前に取るたびに、それは実行されません。そして、server.get()の後に、私はserver.use(express.static('public'));を変更します。server.use()につきました

誰かが私に何か違いを教えてもらえますか?

ここに私のスクリプト:

// Depedencies/built-in 
import express from 'express'; 
import { join } from 'path'; 
import nodeSass from 'node-sass-middleware'; 

// you can place anything here, except depedencies 
import config from './config'; 
import apiRouter from './api/index'; 

const server = express(); 

// Including Middleware 
server.use(nodeSass({ 
    src: join(__dirname + 'sass'), 
    dest: join(__dirname + 'public'), 
})); 

// everytime i take this before Router, it running, but 
// but, the index won't showing up 
server.use(express.static('public')); 

// Setting up view engine 
server.set('view engine', 'ejs'); 

// Router 
server.get('/', (req, res) => { 
    res.render('index', { 
     title: 'Hello EJs', 
    }); 
}); 

// if i change after Route, it working well 
// server.use(express.static('public')); 

server.listen(config.port,() => { 
    console.log('magic happen on port: ', config.port); 
}); 

答えて

0

私が間違って何guesingにより、答えることを試みます。

1) server.use(express.static('public'));これは、JS、CSS、イメージ、およびページが読み込む必要のあるその他の静的ファイルを探す場所をアプリケーションに指示する方法です。詳細はこちら。

2)res.render('pathToRenderFile')を使用すると、指定したエンジンserver.set('view engine', 'ejs');でファイル名を検索しようとします。エンジンが設定されていない場合は、拡張機能も追加する必要があります。デフォルトではviewsディレクトリにあります。詳細はこちらhttp://expressjs.com/en/guide/using-template-engines.html

index.ejsviews/index.ejsに入れる必要があります。それからすべてがうまくいくはずです。

3)ルートの前に、server.useまたはserver.setのようなミドルウェア(ミドルウェア機能)をすべて設定する必要があります。

4)ミドルウェアについて、その点について。任意のルートの前後に、要求オブジェクトまたは応答オブジェクトで必要なアクションを実行できます。たとえば、このミドルウェアhttps://github.com/expressjs/body-parserは、req.bodyオブジェクト内のすべての投稿データを保持する必要があります。あなたがそれを含んでいなければ、それをあなた自身で解析する必要があります。そのためExpressは、ビルドインやミドルウェアを使用して、このケースを処理する良い方法を提供します。ここ

したがってミドルウェア包含の順序が重要である、https://expressjs.com/en/resources/middleware.html

ミドルウェア機能が順次実行されるすべての便利なミドルウェアのリストです。

は、このことができますここでは良い例https://expressjs.com/en/4x/api.html#app.use

希望があります。

+0

答えてくれてありがとう、私はこれを私のメモに書きます。 – AinulBedjo

+0

viewsディレクトリ内にindex.ejsを作成する必要がありますが、何も変更されていません Umm ..私は 'server.use(express.static( 'public'))'を '起こりました。私はちょうど 'server.use(express.static( 'public'))'を取る方法を知りませんし、もし上または下を取ると違いは – AinulBedjo

+0

あなたは 'server.use(express.static(__ dirname + '/ public')) '? –

関連する問題