2016-12-02 4 views
2

NodeJS에서 가장 먼저 시도한 것으로, 방문자에게 IP 주소를 알려주는 HTML 페이지를 표시하는 간단한 앱을 작성하고 있습니다.TypeError : Express에서 JS를 사용하려고 할 때 this.engine이 함수가 아닙니다.

TypeError: this.engine is not a function 
    at View.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/view.js:126:8) 
    at tryRender (/Users/macuser/NodeJS/hello/node_modules/express/lib/application.js:639:10) 
    at EventEmitter.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/application.js:591:3) 
    at ServerResponse.render (/Users/macuser/NodeJS/hello/node_modules/express/lib/response.js:960:7) 
    at /Users/macuser/NodeJS/hello/index.js:8:9 
    at Layer.handle [as handle_request] (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/layer.js:95:5) 
    at next (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/route.js:131:13) 
    at Route.dispatch (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/route.js:112:3) 
    at Layer.handle [as handle_request] (/Users/macuser/NodeJS/hello/node_modules/express/lib/router/layer.js:95:5) 
    at /Users/macuser/NodeJS/hello/node_modules/express/lib/router/index.js:277:22 
:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Hello, World!</title> 
    </head> 
    <body> 
     <h1>Hello, World!</h1> 
     <hr> 
     <p>If you're reading this, the NodeJS setup is working. Check your developer console. See if there's any HTTP error in there.</p> 
     <p>Anyway, your IP address is {{ip}}</p> 
    </body> 
</html> 

그리고 여기에 내가 요청을 보낼 제가 콘솔의 모든 시간을 얻을 : 여기

여기 /views/frontPage.html의 모습 방법

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

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

app.get('/', function (req, res) { 
    res.setHeader('Content-Type', 'text/html'); // Do I have to do this? I'm not sure. 
    res.render('frontPage.html', { 
     ip: req.ip 
    }); 
res.send(); 
}); 

app.listen(8080, function() { 
    console.log("Listening on port 8080"); 
}); 

처럼 보이는 방법

views/ 안에 이미 frontPage.html을 설정하고 I a NPM (npm install mu2 --save)의 콧수염을 이미 설치했습니다. 무엇이 문제입니까?

+1

몇 가지 조사를 한 후 Express와 Mustache의 호환성에 대한 모순이 있음을 발견했습니다. 웹 사이트의 가이드가 호환성이 있다고하더라도, Mustache는이 목록에 없습니다. https://github.com/expressjs/express/wiki?_ga=1.74621138.1527575629.1480681917#template-engines – starleaf1

답변

1

expressjs.com에서 나는 익스프레스 '템플릿 시스템을 우회 끝내었고, 콧수염 자신의 compileAndRender()를 사용합니다. 좋아요 :

var express = require('express'); 
var app = express(); 
var mu2 = require('mu2'); 
mu2.root = __dirname + '/views'; 

app.get('/', function (req, res) { 
    var htmlStream = mu2.compileAndRender('frontPage.html', {ip: req.ip}); 
    htmlStream.pipe(res); 
}); 

app.listen(8080, function() { 
    console.log("Listening on port 8080"); 
}); 

이제 작동합니다.

0

파일 확장자를 .html에서 μ2로 변경해야합니다. res.render('frontPage.mu2', { ip: req.ip});은 HTML 파일이 아닌 Mustache 파일이므로 또한 기본 뷰 렌더러를 mu2로 설정 했으므로 파일 확장자를 해제 할 수 있으며, 익스프레스는 파일 확장자가 제공되지 않으면이를 렌더링 엔진으로 사용합니다. 좋아요 ... res.render('frontPage', {ip: req.ip});. 첫 번째 부분은 파일 경로 '/ frontPage'이고 두 번째 부분은 템플릿에 전달할 로컬 객체입니다. 당신은 당신의 μ2 파일 안에이 {{ip}}과 같은 객체의 ip 속성에 접근 할 것입니다. 콧수염은 표현할 렌더링 된 HTML을 반환하고 res.render는이를 클라이언트로 보냅니다.

또한 res.render()가 뷰를 렌더링하고 렌더링 된 HTML 문자열을 클라이언트에 전송하므로 res.send()가 필요하지 않으며 text/html도 응답 또는 String 유형으로 간주되므로, res.setHeader ('Content-Type', 'text-html'); 필요하지 않습니다. 그러나 어느 쪽이든. ;)

res.render(view [, locals] [, callback]) Renders a view and sends the rendered HTML string to the client. Optional parameters:

locals, an object whose properties define local variables for the view.

callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via require()) and render it using the loaded module’s __express function.

+0

그래서 헤더 선언을 삭제했습니다. ,'send()', 그리고 템플릿 파일의 확장자. 나는 또한'frontPage.html'을'frontPage.mu2'로 이름을 바꾸어'view'의 시작 부분에'/'를 추가했습니다. 불행히도, 이제'view 디렉토리를 보지 못했습니다 '/ frontPage'/ views users/macuser/NodeJS '라고 말하고 있습니다./hello/views "' – starleaf1

+0

"/ "없이 시도 했습니까? res.render ('frontPage', {ip : req.ip}); – quarterpi

+0

원래 오류로 곧장 돌아갑니다. – starleaf1