简体   繁体   English

使用express在node js中提供html文件

[英]serving html files in node js using express

actally i'm trying to serve a html file in the browser using node js and express. 实际上,我正在尝试使用节点js和express在浏览器中提供html文件。 unfortunatly i can't get the correct appearence of the html file. 不幸的是,我无法正确显示html文件。

here is the code : 这是代码:

var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client

var server = http.createServer(function(req, res) {
    fs.readFile('./table.html', 'utf-8', function(error, content) {

        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});

To send a single file for a specific route use the res.sendFile() function. 要为特定路由发送单个文件,请使用res.sendFile()函数。

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

var path = require('path');

app.get('/', function(req, res) {
    res.sendFile(path.resolve('path/to/my/file.html'));
});

app.listen(3000);

In case you want to serve all files in a directory use the express.static() middleware 如果您要提供目录中的所有文件,请使用express.static()中间件

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

app.use(express.static('path/to/my/directory'));

app.listen(3000);

With express u can do something like 有了Express,您可以做类似的事情

//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
   app.use(express.static("./file"));
})
server.listen(8000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM