我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
我试图找出如何加载和呈现一个基本的HTML文件,这样我就不必写代码:
response.write('...<p>blahblahblah</p>...');
当前回答
您可以使用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}...`);
其他回答
我认为这将是一个更好的选择,因为它显示了运行服务器的URL:
var http = require('http'),
fs = require('fs');
const hostname = '<your_machine_IP>';
const port = 3000;
const html=fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
})
});
使用快递模块怎么样?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
然后,可以使用浏览器获取/localhost:8000
我学到的最好的方法是在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");
干净而且最好!!
你可以直接在end方法中加载HTML
response.end('...<p>blahblahblah</p>...')
这和
response.write('...<p>blahblahblah</p>...')
response.end()
这是一个相当老的问题……但如果你在这里的用例是简单地向浏览器发送一个特定的HTML页面,我会使用像这样简单的东西:
var http = require('http')
, fs = require('fs');
var server = http.createServer(function(req, res){
var stream = fs.createReadStream('test.html');
stream.pipe(res);
});
server.listen(7000);