Programing

기본 HTML 뷰를 렌더링 하시겠습니까?

lottogame 2020. 3. 27. 07:59
반응형

기본 HTML 뷰를 렌더링 하시겠습니까?


Express 프레임 워크를 사용하여 시작하려고하는 기본 node.js 앱이 있습니다. 파일 이있는 views폴더가 index.html있습니다. 그러나 웹 브라우저를로드 할 때 다음 오류가 발생합니다.

오류 : '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')

내가 여기서 무엇을 놓치고 있습니까?


옥에 일반 HTML 페이지를 포함시킬 수 있습니다.

views / index.jade에서

include plain.html

views / plain.html에서

<!DOCTYPE html>
...

app.js는 여전히 옥을 렌더링 할 수 있습니다.

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는 뷰 시스템에를require('ejs') 로드 할 것입니다.로드되는 모듈은 Express를 준수하기 위해 메소드exports.render(str, options)내 보내야 하지만 app.register()엔진을 파일 확장자에 맵핑하는 데 사용될 foo.html수 있으므로 jade에 의해 렌더링 될 수 있습니다.

따라서 자신 만의 간단한 렌더러를 만들거나 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');
});

express@~3.0.0을 사용하는 경우 예제에서 아래 행을 변경하십시오.

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

이런 식으로 :

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

Express 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.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 템플릿을보기 엔진으로 사용하는 것입니다. 거기에서 * .ejs보기 파일에 원시 HTML을 작성할 수 있습니다.


views 디렉토리 를 사용할 필요가 없다면 html 파일을 아래 공용 디렉토리 로 옮기 십시오.

그런 다음이 줄을 '/ views'대신 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에서 두 줄만 주석 처리하면됩니다.

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

익스프레스 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)
});

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. package.json 파일에서 "jade"를 "ejs"로 바꾸고 "XYZ"(버전)를 "*"로 바꾸십시오.

      "dependencies": {
       "ejs": "*"
      }
    
  2. 그런 다음 app.js 파일에서 다음 코드를 추가하십시오.

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

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

  3. 그리고 모든 .HTML 파일을 views 폴더에 보관하십시오.

건배 :)


이전에 정적 미들웨어에 의해 처리되었던 Express 경로로 "/"에 대한 요청을 처리하고 싶었습니다. 그러면 응용 프로그램 설정에 따라 일반 버전의 index.html 또는 연결된 + 축소 된 JS 및 CSS를로드 한 버전을 렌더링 할 수 있습니다. Andrew Homeyer의 답변 에서 영감을 받아 HTML 파일을 수정하지 않은 상태로 views 폴더로 드래그하고 Express를 다음과 같이 구성하기로 결정했습니다.

   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 파일을 제공하려고하면 '렌더링'할 필요가 없으며 '서빙'해야합니다. 렌더링은 페이지를 브라우저로 보내기 전에 서버를 업데이트하거나 콘텐츠를 주입하는 경우이며, 다른 답변이 표시하는 것처럼 ejs와 같은 추가 종속성이 필요합니다.

요청에 따라 브라우저를 파일로 보내려면 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 디렉토리의 내용을 공유하므로주의하십시오.

나는 그것이 도움이되기를 바랍니다


node.js에 Express 프레임 워크를 사용하는 경우

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는 ejs 파일 이름의 확장자를 가진 views 디렉토리에 html 파일이 있습니다. form.html.ejs

그런 다음 form.js를 작성하십시오.

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

참고 URL : https://stackoverflow.com/questions/4529586/render-basic-html-view

반응형