我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
我学到的最好的方法是在html文件中使用express,因为express有很多优势。如果你想的话,你也可以把它扩展到Heroku平台上。
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3000);
console.log("Running at Port 3000");
干净而且最好!!
其他回答
您可以使用Express使用Node加载和呈现基本的HTML文件。这大约需要10分钟才能开始。它被绑定到http.createServer(),所以你仍然在Node的土地上,可以轻松地删除它。
// app.js
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', express.static('index.html'));
app.use('/test', express.static('test.html'));
module.exports = app;
// server.js
const http = require('http');
const PORT = process.env.PORT || 3000;
const appServer = require('./app');
const httpServer = http.createServer(appServer);
httpServer.listen(PORT);
console.log(`Listening on port ${PORT}...`);
我知道这是一个老问题,但由于没有人提到过,我认为有必要补充一下:
如果你真的想要提供静态内容(比如一个“关于”页面,图像,css等),你可以使用一个静态内容服务模块,例如node-static。(还有其他可能更好或更差的方法——试试search.npmjs.org。)通过一点点预处理,您就可以从静态页面中过滤动态页面,并将它们发送到正确的请求处理程序。
采用管道法是一种更加灵活、简单的方法。
var fs = require('fs');
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
var file = fs.createReadStream('index.html');
file.pipe(response);
}).listen(8080);
console.log('listening on port 8080...');
var http = require('http');
var fs = require('fs'); //required to readfile
http.createServer(function(req, response){
fs.readFile('index.html',function (err, data){
response.writeHead(200);
response.write(data);
response.end();
});
}).listen(8000);
// #just use express lol
Index.html是HTML文件的名称
用ejs代替jade
npm 安装 EJS
app.js
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/线路/ index.js
exports.index = function(req, res){
res.render('index', { title: 'ejs' });};