简体   繁体   English

使用 Node.js 作为简单的 Web 服务器

[英]Using Node.js as a simple web server

I want to run a very simple HTTP server.我想运行一个非常简单的 HTTP 服务器。 Every GET request to example.com should get index.html served to it but as a regular HTML page (ie, same experience as when you read normal web pages).example.com每个 GET 请求都应该将index.html作为常规 HTML 页面提供给它(即,与您阅读普通网页时的体验相同)。

Using the code below, I can read the content of index.html .使用下面的代码,我可以读取index.html的内容。 How do I serve index.html as a regular web page?如何将index.html作为常规网页提供?

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(index);
}).listen(9615);

One suggestion below is complicated and requires me to write a get line for each resource (CSS, JavaScript, images) file I want to use.下面的一个建议很复杂,需要我为我想要使用的每个资源(CSS、JavaScript、图像)文件编写一个get行。

How can I serve a single HTML page with some images, CSS and JavaScript?如何使用一些图像、CSS 和 JavaScript 为单个 HTML 页面提供服务?

Simplest Node.js server is just:最简单的 Node.js 服务器就是:

$ npm install http-server -g

Now you can run a server via the following commands:现在您可以通过以下命令运行服务器:

$ cd MyApp

$ http-server

If you're using NPM 5.2.0 or newer, you can use http-server without installing it with npx .如果您使用的是 NPM 5.2.0 或更新版本,您可以使用http-server而无需使用npx安装它。 This isn't recommended for use in production but is a great way to quickly get a server running on localhost.不建议在生产中使用它,但它是快速让服务器在 localhost 上运行的好方法。

$ npx http-server

Or, you can try this, which opens your web browser and enables CORS requests:或者,您可以尝试此操作,它会打开您的 Web 浏览器并启用 CORS 请求:

$ http-server -o --cors

For more options, check out the documentation for http-server on GitHub , or run:有关更多选项,请查看GitHub 上的http-server文档,或运行:

$ http-server --help

Lots of other nice features and brain-dead-simple deployment to NodeJitsu.许多其他不错的功能和对 NodeJit 的简单部署。

Feature Forks功能叉

Of course, you can easily top up the features with your own fork.当然,您可以使用自己的分叉轻松地充值功能。 You might find it's already been done in one of the existing 800+ forks of this project:您可能会发现它已经在该项目现有的 800 多个分支之一中完成:

Light Server: An Auto Refreshing Alternative Light Server:自动刷新的替代方案

A nice alternative to http-server is light-server . http-server一个不错的替代方案是light-server It supports file watching and auto-refreshing and many other features.它支持文件监视和自动刷新以及许多其他功能。

$ npm install -g light-server 
$ light-server

Add to your directory context menu in Windows Explorer添加到 Windows 资源管理器中的目录上下文菜单

 reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""

Simple JSON REST server简单的 JSON REST 服务器

If you need to create a simple REST server for a prototype project then json-server might be what you're looking for.如果您需要为原型项目创建一个简单的 REST 服务器,那么json-server可能就是您要找的。

Auto Refreshing Editors自动刷新编辑器

Most web page editors and IDE tools now include a web server that will watch your source files and auto refresh your web page when they change.大多数网页编辑器和 IDE 工具现在都包含一个 Web 服务器,该服务器将监视您的源文件并在它们更改时自动刷新您的网页。

I use Live Server with Visual Studio Code.我将Live Server与 Visual Studio Code 一起使用。

The open source text editor Brackets also includes a NodeJS static web server.开源文本编辑器Brackets还包括一个 NodeJS 静态 Web 服务器。 Just open any HTML file in Brackets, press " Live Preview " and it starts a static server and opens your browser at the page.只需在 Brackets 中打开任何 HTML 文件,按“实时预览”,它就会启动一个静态服务器并在页面上打开您的浏览器。 The browser will auto refresh whenever you edit and save the HTML file.每当您编辑和保存 HTML 文件时,浏览器都会自动刷新 This especially useful when testing adaptive web sites.这在测试自适应网站时特别有用。 Open your HTML page on multiple browsers/window sizes/devices.在多个浏览器/窗口大小/设备上打开您的 HTML 页面。 Save your HTML page and instantly see if your adaptive stuff is working as they all auto refresh.保存您的 HTML 页面并立即查看您的自适应内容是否正常工作,因为它们都会自动刷新。

Web / SPA / PWA / Mobile / Desktop / Browser Ext Web Developers Web / SPA / PWA / 移动 / 桌面 / 浏览器 Ext Web 开发人员

Some SPA frameworks include a built in version of the Webpack DevServer that can detect source file changes and trigger an incremental rebuild and patch (called hot reloading) of your SPA or PWA web app.一些 SPA 框架包含一个内置版本的Webpack DevServer ,可以检测源文件更改并触发 SPA 或 PWA Web 应用程序的增量重建和补丁(称为热重载)。 Here's a few popular SPA frameworks that can do this.这里有一些流行的 SPA 框架可以做到这一点。

VueJS Developers VueJS 开发人员

For VueJS developers, a favorite is Quasar Framework that includes the Webpack DevServer out of the box with switches to support server-side rendering (SSR) and proxy rules to cure your CORS issues.对于 VueJS 开发人员来说,最喜欢的是Quasar Framework ,它包括开箱即用的 Webpack DevServer,带有支持服务器端渲染 (SSR) 和代理规则的开关,以解决您的 CORS 问题。 It includes a large number of optimized components designed to adapt for both Mobile and Desktop.它包括大量优化的组件,旨在适应移动和桌面。 These allows you to build one app for ALL platforms (SPA, SPA+SSR, PWA, PWA+SSR, Cordova and Capacitor Mobile AppStore apps, Electron Desktop Node+VueJS apps and even Browser extensions).这允许你建立适用于所有平台(SPA,SPA + SSR,PWA,PWA + SSR,科尔多瓦和电容移动AppStore的应用程序,电子桌面节点+ VueJS应用程式,甚至浏览器扩展)一个应用程序

Another popular one is NuxtJS that also supports static HTML/CSS code generation as well as SSR or no-SSR build modes with plugins for other UI component suites.另一个流行的是NuxtJS ,它也支持静态 HTML/CSS 代码生成以及 SSR 或无 SSR 构建模式,以及其他 UI 组件套件的插件。

React Framework Developers反应框架开发人员

ReactJS developers can also setup hot reloading . ReactJS开发人员还可以设置热重载

Cordova/Capacitor + Ionic Framework Developers Cordova/电容器 + 离子框架开发人员

Iconic is a mobile only hybrid component framework that now supports VueJS, React and Angular development. Iconic 是一个仅限移动设备的混合组件框架,现在支持 VueJS、React 和 Angular 开发。 A local server with auto refresh features is baked into the ionic tool.具有自动刷新功能的本地服务器被烘焙到ionic工具中。 Just run ionic serve from your app folder.只需从您的应用程序文件夹运行ionic serve Even better ... ionic serve --lab to view auto-refreshing side by side views of both iOS and Android.更好的是... ionic serve --lab可以并排查看iOS和Android的自动刷新视图。

Note : This answer is from 2011. However, it is still valid.注意:这个答案是从 2011 年开始的。但是,它仍然有效。

You can use Connect and ServeStatic with Node.js for this:您可以将ConnectServeStatic与 Node.js 结合使用:

  1. Install connect and serve-static with NPM使用 NPM 安装连接和静态服务

     $ npm install connect serve-static
  2. Create server.js file with this content:使用以下内容创建 server.js 文件:

     var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () => console.log('Server running on 8080...'));
  3. Run with Node.js使用 Node.js 运行

     $ node server.js

You can now go to http://localhost:8080/yourfile.html您现在可以访问http://localhost:8080/yourfile.html

Check out this gist .看看这个要点 I'm reproducing it here for reference, but the gist has been regularly updated.我在这里复制以供参考,但要点已定期更新。

Node.JS static file web server. Node.JS 静态文件 Web 服务器。 Put it in your path to fire up servers in any directory, takes an optional port argument.将它放在您的路径中以启动任何目录中的服务器,采用可选的端口参数。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

Update更新

The gist does handle css and js files.要点确实处理 css 和 js 文件。 I've used it myself.我自己用过。 Using read/write in "binary" mode isn't a problem.在“二进制”模式下使用读/写不是问题。 That just means that the file isn't interpreted as text by the file library and is unrelated to content-type returned in the response.这只是意味着文件不会被文件库解释为文本,并且与响应中返回的内容类型无关。

The problem with your code is you're always returning a content-type of "text/plain".您的代码的问题是您总是返回“文本/纯文本”的内容类型。 The above code does not return any content-type, but if you're just using it for HTML, CSS, and JS, a browser can infer those just fine.上面的代码不返回任何内容类型,但如果你只是将它用于 HTML、CSS 和 JS,浏览器可以很好地推断出它们。 No content-type is better than a wrong one.没有内容类型比错误的内容类型更好。

Normally the content-type is a configuration of your web server.通常,内容类型是您的 Web 服务器的配置。 So I'm sorry if this doesn't solve your problem, but it worked for me as a simple development server and thought it might help some other people.因此,如果这不能解决您的问题,我很抱歉,但它作为一个简单的开发服务器对我有用,并认为它可能会帮助其他一些人。 If you do need correct content-types in the response, you either need to explicitly define them as joeytwiddle has or use a library like Connect that has sensible defaults.如果您在响应中确实需要正确的内容类型,您要么需要像 joeytwiddle 那样明确定义它们,要么使用像 Connect 这样具有合理默认值的库。 The nice thing about this is that it's simple and self-contained (no dependencies).这样做的好处是它简单且自包含(无依赖关系)。

But I do feel your issue.但我确实感觉到你的问题。 So here is the combined solution.所以这是组合解决方案。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  var contentTypesByExtension = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript"
  };

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      var contentType = contentTypesByExtension[path.extname(filename)];
      if (contentType) headers["Content-Type"] = contentType;
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

You don't need express.你不需要快递。 You don't need connect.你不需要连接。 Node.js does http NATIVELY. Node.js 原生地执行 http。 All you need to do is return a file dependent on the request:您需要做的就是根据请求返回一个文件:

var http = require('http')
var url = require('url')
var fs = require('fs')

http.createServer(function (request, response) {
    var requestUrl = url.parse(request.url)    
    response.writeHead(200)
    fs.createReadStream(requestUrl.pathname).pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync) 
}).listen(9615)    

A more full example that ensures requests can't access files underneath a base-directory, and does proper error handling:一个更完整的示例,可确保请求无法访问基目录下的文件,并进行正确的错误处理:

var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname   // or whatever base directory you want

var port = 9615

http.createServer(function (request, response) {
    try {
        var requestUrl = url.parse(request.url)

        // need to use path.normalize so people can't access directories underneath baseDirectory
        var fsPath = baseDirectory+path.normalize(requestUrl.pathname)

        var fileStream = fs.createReadStream(fsPath)
        fileStream.pipe(response)
        fileStream.on('open', function() {
             response.writeHead(200)
        })
        fileStream.on('error',function(e) {
             response.writeHead(404)     // assume the file doesn't exist
             response.end()
        })
   } catch(e) {
        response.writeHead(500)
        response.end()     // end the response so browsers don't hang
        console.log(e.stack)
   }
}).listen(port)

console.log("listening on port "+port)

I think the part you're missing right now is that you're sending:我认为您现在缺少的部分是您正在发送:

Content-Type: text/plain

If you want a web browser to render the HTML, you should change this to:如果您希望 Web 浏览器呈现 HTML,则应将其更改为:

Content-Type: text/html

Step1 (inside command prompt [I hope you cd TO YOUR FOLDER]) : npm install express Step1(在命令提示符内[我希望你 cd 到你的文件夹]): npm install express

Step 2: Create a file server.js第 2 步:创建文件 server.js

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder

app.get("/", function(request, response){ //root dir
    response.send("Hello!!");
});

app.listen(port, host);

Please note, you should add WATCHFILE (or use nodemon) too.请注意,您也应该添加 WATCHFILE(或使用 nodemon)。 Above code is only for a simple connection server.以上代码仅适用于简单的连接服务器。

STEP 3: node server.js or nodemon server.js第 3 nodemon server.jsnode server.jsnodemon server.js

There is now more easy method if you just want host simple HTTP server.如果您只想托管简单的 HTTP 服务器,现在有更简单的方法。 npm install -g http-server

and open our directory and type http-server并打开我们的目录并输入http-server

https://www.npmjs.org/package/http-server https://www.npmjs.org/package/http-server

The fast way:快捷方式:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });

Your way:你的方式:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    console.dir(req.url);

    // will get you  '/' or 'index.html' or 'css/styles.css' ...
    // • you need to isolate extension
    // • have a small mimetype lookup array/object
    // • only there and then reading the file
    // •  delivering it after setting the right content type

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

    res.end('ok');
}).listen(3001);

Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:与其处理 switch 语句,我认为从字典中查找内容类型更简洁:

var contentTypesByExtension = {
    'html': "text/html",
    'js':   "text/javascript"
};

...

    var contentType = contentTypesByExtension[fileExtension] || 'text/plain';

This is basically an updated version of the accepted answer for connect version 3:这基本上是已接受的连接版本 3 答案的更新版本:

var connect = require('connect');
var serveStatic = require('serve-static');

var app = connect();

app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);

I also added a default option so that index.html is served as a default.我还添加了一个默认选项,以便将 index.html 作为默认选项。

You don't need to use any NPM modules to run a simple server, there's a very tiny library called " NPM Free Server " for Node:你不需要使用任何 NPM 模块来运行一个简单的服务器,Node 有一个名为“ NPM Free Server ”的非常小的库:

50 lines of code, outputs if you are requesting a file or a folder and gives it a red or green color if it failed for worked. 50 行代码,如果您请求文件或文件夹,则输出,如果工作失败,则将其显示为红色或绿色。 Less than 1KB in size (minified).小于 1KB(缩小)。

if you have node installed on you PC probably you have the NPM, if you don't need NodeJS stuff, you can use the serve package for this:如果你的 PC 上安装了 node,你可能有 NPM,如果你不需要 NodeJS 的东西,你可以使用serve包:

1 - Install the package on your PC: 1 - 在您的 PC 上安装软件包:

npm install -g serve

2 - Serve your static folder: 2 - 为您的静态文件夹提供服务:

serve <path> 
d:> serve d:\StaticSite

It will show you which port your static folder is being served, just navigate to the host like:它将显示您的静态文件夹正在服务哪个端口,只需导航到主机,如:

http://localhost:3000

You can just type those in your shell你可以在你的 shell 中输入这些

npx serve

Repo: https://github.com/zeit/serve .回购: https : //github.com/zeit/serve

I found a interesting library on npm that might be of some use to you.我在 npm 上发现了一个有趣的库,可能对你有用。 It's called mime( npm install mime or https://github.com/broofa/node-mime ) and it can determine the mime type of a file.它被称为 mime( npm install mimehttps://github.com/broofa/node-mime ),它可以确定文件的 mime 类型。 Here's an example of a webserver I wrote using it:这是我使用它编写的网络服务器示例:

var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path  = unescape(__dirname + req.url)
var code = 200
 if(fs.existsSync(path)) {
    if(fs.lstatSync(path).isDirectory()) {
        if(fs.existsSync(path+"index.html")) {
        path += "index.html"
        } else {
            code = 403
            resp.writeHead(code, {"Content-Type": "text/plain"});
            resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
        }
    }
    resp.writeHead(code, {"Content-Type": mime.lookup(path)})
    fs.readFile(path, function (e, r) {
    resp.end(r);

})
} else {
    code = 404
    resp.writeHead(code, {"Content-Type":"text/plain"});
    resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")

This will serve any regular text or image file (.html, .css, .js, .pdf, .jpg, .png, .m4a and .mp3 are the extensions I've tested, but it theory it should work for everything)这将提供任何常规文本或图像文件(.html、.css、.js、.pdf、.jpg、.png、.m4a 和 .mp3 是我测试过的扩展名,但理论上它应该适用于所有内容)

Developer Notes开发者笔记

Here is an example of output that I got with it:这是我用它得到的输出示例:

Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg

Notice the unescape function in the path construction.注意路径构造中的unescape函数。 This is to allow for filenames with spaces and encoded characters.这是为了允许带有空格和编码字符的文件名。

Edit:编辑:

Node.js sample app Node Chat has the functionality you want. Node.js 示例应用程序节点聊天具有您想要的功能。
In it's README.textfile在它的README.textfile
3. Step is what you are looking for. 3. Step 是你要找的。

step1第1步

  • create a server that responds with hello world on port 8002创建一个在端口 8002 上响应 hello world 的服务器

step2第2步

  • create an index.html and serve it创建一个 index.html 并提供它

step3第三步

  • introduce util.js介绍 util.js
  • change the logic so that any static file is served更改逻辑以便提供任何静态文件
  • show 404 in case no file is found如果找不到文件,则显示 404

step4第四步

  • add jquery-1.4.2.js添加 jquery-1.4.2.js
  • add client.js添加客户端.js
  • change index.html to prompt user for nickname更改 index.html 以提示用户输入昵称

Here is the server.js这是server.js

Here is the util.js这是util.js

The way I do it is to first of all install node static server globally via我这样做的方法是首先通过全局安装节点静态服务器

npm install node-static -g

then navigate to the directory that contains your html files and start the static server with static .然后导航到包含您的 html 文件的目录并使用static启动静态服务器。

Go to the browser and type localhost:8080/"yourHtmlFile" .转到浏览器并输入localhost:8080/"yourHtmlFile"

Basically copying the accepted answer, but avoiding creating a js file.基本上是复制接受的答案,但避免创建 js 文件。

$ node
> var connect = require('connect'); connect().use(static('.')).listen(8000);

Found it very convinient.发现它非常方便。

Update更新

As of latest version of Express, serve-static has become a separate middleware.在最新版本的 Express 中,serve-static 已经成为一个独立的中间件。 Use this to serve:使用它来服务:

require('http').createServer(require('serve-static')('.')).listen(3000)

Install serve-static first.首先安装serve-static

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    // change the to 'text/plain' to 'text/html' it will work as your index page
    res.end(index);
}).listen(9615);

I think you where searching for this.我想你在哪里寻找这个。 In your index.html, simply fill it with normal html code - whatever you want to render on it, like:在你的 index.html 中,简单地用普通的 html 代码填充它 - 无论你想在它上面呈现什么,比如:

<html>
    <h1>Hello world</h1>
</html>

I use below code to start a simple web server which render default html file if no file mentioned in Url.我使用下面的代码来启动一个简单的 Web 服务器,如果 Url 中没有提到文件,它会呈现默认的 html 文件。

var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic   Geek Files.htm';


http.createServer(function(req, res){

    var fileName = url.parse(req.url).pathname;
    // If no file name in Url, use default file name
    fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;

    fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
        if (content != null && content != '' ){
            res.writeHead(200,{'Content-Length':content.length});
            res.write(content);
        }
        res.end();
    });

}).listen(8800);

It will render all js, css and image file, along with all html content.它将呈现所有 js、css 和图像文件,以及所有 html 内容。

Agree on statement " No content-type is better than a wrong one "同意声明“没有内容类型总比错误的好

from w3schools来自 w3schools

it is pretty easy to create a node server to serve any file that is requested, and you dont need to install any packages for it创建一个节点服务器来为请求的任何文件提供服务非常容易,并且您不需要为其安装任何软件包

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }  
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

http://localhost:8080/file.html http://localhost:8080/file.html

will serve file.html from disk将从磁盘提供 file.html

I'm not sure if this is exactly what you wanted, however, you can try changing:我不确定这是否正是您想要的,但是,您可以尝试更改:

{'Content-Type': 'text/plain'}

to this:对此:

{'Content-Type': 'text/html'}

This will have the browser client display the file as html instead of plain text.这将使浏览器客户端将文件显示为 html 而不是纯文本。

Express function sendFile does exactly what you need, and since you want web server functionality from node, express comes as natural choice and then serving static files becomes as easy as : Express 函数 sendFile 正是您所需要的,并且由于您希望从节点获得 Web 服务器功能,因此 Express 成为自然选择,然后提供静态文件变得如此简单:

res.sendFile('/path_to_your/index.html')

read more here : https://expressjs.com/en/api.html#res.sendFile在这里阅读更多: https : //expressjs.com/en/api.html#res.sendFile

A small example with express web server for node:一个带有用于节点的快速 Web 服务器的小示例:

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(8080);

run this, and navigate to http://localhost:8080运行它,并导航到http://localhost:8080

To expand on this to allow you to serve static files like css and images, here's another example :为了扩展这一点以允许您提供诸如 css 和图像之类的静态文件,这是另一个示例:

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

app.use(express.static(__dirname + '/css'));

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8080);

so create a subfolder called css, put your static content in it, and it will be available to your index.html for easy reference like :因此,创建一个名为 css 的子文件夹,将您的静态内容放入其中,它将可用于您的 index.html 以便于参考,例如:

<link type="text/css" rel="stylesheet" href="/css/style.css" />

Notice relative path in href!注意 href 中的相对路径!

voila!瞧!

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);

//Just Change The CONTENT TYPE to 'html'

A slightly more verbose express 4.x version but that provides directory listing, compression, caching and requests logging in a minimal number of lines一个稍微详细一点的 express 4.x 版本,但它提供目录列表、压缩、缓存和请求以最少的行数记录

var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express

var app = express();

var oneDay = 86400000;

app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))

app.listen(process.env.PORT || 8000);

console.log("Ready To serve files !")

Crazy amount of complicated answers here.这里有大量复杂的答案。 If you don't intend to process nodeJS files/database but just want to serve static html/css/js/images as your question suggest then simply install the pushstate-server module or similar;如果您不打算处理 nodeJS 文件/数据库,而只想按照您的问题建议提供静态 html/css/js/images,那么只需安装pushstate-server模块或类似模块;

Here's a "one liner" that will create and launch a mini site.这是一个“one liner”,它将创建和启动一个迷你站点。 Simply paste that entire block in your terminal in the appropriate directory.只需将整个块粘贴到终端中的相应目录中即可。

mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js

Open browser and go to http://localhost:3000 .打开浏览器并转到http://localhost:3000 Done.完毕。

The server will use the app dir as the root to serve files from.服务器将使用app目录作为根来提供文件。 To add additional assets just place them inside that directory.要添加其他资产,只需将它们放在该目录中。

There are already some great solutions for a simple nodejs server .对于简单的nodejs server已经有一些很好的解决方案。 There is a one more solution if you need live-reloading as you made changes to your files.如果您在更改文件时需要live-reloading ,还有一个解决方案。

npm install lite-server -g

navigate your directory and do导航您的目录并执行

lite-server

it will open browser for you with live-reloading.它将通过实时重新加载为您打开浏览器。

Most of the answers above describe very nicely how contents are being served.上面的大多数答案都很好地描述了如何提供内容。 What I was looking as additional was listing of the directory so that other contents of the directory can be browsed.我正在寻找的附加内容是目录列表,以便可以浏览目录的其他内容。 Here is my solution for further readers:这是我为更多读者提供的解决方案:

'use strict';

var finalhandler = require('finalhandler');
var http = require('http');
var serveIndex = require('serve-index');
var serveStatic = require('serve-static');
var appRootDir = require('app-root-dir').get();
var log = require(appRootDir + '/log/bunyan.js');

var PORT = process.env.port || 8097;

// Serve directory indexes for reports folder (with icons)
var index = serveIndex('reports/', {'icons': true});

// Serve up files under the folder
var serve = serveStatic('reports/');

// Create server
var server = http.createServer(function onRequest(req, res){
    var done = finalhandler(req, res);
    serve(req, res, function onNext(err) {
    if (err)
        return done(err);
    index(req, res, done);
    })
});


server.listen(PORT, log.info('Server listening on: ', PORT));

The simpler version which I've came across is as following.我遇到的更简单的版本如下。 For education purposes, it is best, because it does not use any abstract libraries.出于教育目的,这是最好的,因为它不使用任何抽象库。

var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');

var mimeTypes = {
  "html": "text/html",
  "mp3":"audio/mpeg",
  "mp4":"video/mp4",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"};

http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname;
    var filename = path.join(process.cwd(), uri);
    fs.exists(filename, function(exists) {
        if(!exists) {
            console.log("not exists: " + filename);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write('404 Not Found\n');
            res.end();
            return;
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, {'Content-Type':mimeType});

        var fileStream = fs.createReadStream(filename);
        fileStream.pipe(res);

    }); //end path.exists
}).listen(1337);

Now go to browser and open following:现在转到浏览器并打开以下内容:

http://127.0.0.1/image.jpg

Here image.jpg should be in same directory as this file.这里image.jpg应该和这个文件在同一个目录下。 Hope this helps someone :)希望这对某人有所帮助:)

local-web-server is definitely worth a look!本地网络服务器绝对值得一看! Here's an excerpt from the readme:这是自述文件的摘录:

local-web-server本地网络服务器

A lean, modular web server for rapid full-stack development.用于快速全栈开发的精益模块化 Web 服务器。

  • Supports HTTP, HTTPS and HTTP2.支持 HTTP、HTTPS 和 HTTP2。
  • Small and 100% personalisable.小巧且 100% 个性化。 Load and use only the behaviour required by your project.仅加载和使用项目所需的行为。
  • Attach a custom view to personalise how activity is visualised.附加自定义视图以个性化活动的可视化方式。
  • Programmatic and command-line interfaces.编程和命令行界面。

Use this tool to:使用此工具:

  • Build any type of front-end web application (static, dynamic, Single Page App, Progessive Web App, React etc).构建任何类型的前端 Web 应用程序(静态、动态、单页应用程序、渐进式 Web 应用程序、React 等)。
  • Prototype a back-end service (REST API, microservice, websocket, Server Sent Events service etc).原型后端服务(REST API、微服务、websocket、服务器发送事件服务等)。
  • Monitor activity, analyse performance, experiment with caching strategy etc.监控活动、分析性能、试验缓存策略等。

Local-web-server is a distribution of lws bundled with a "starter pack" of useful middleware. Local-web-server 是一个lws的发行版,捆绑了一个有用的中间件的“入门包”。

Synopsis概要

This package installs the ws command-line tool (take a look at the usage guide ).这个包安装了ws命令行工具(查看使用指南)。

Static web site静态网站

Running ws without any arguments will host the current directory as a static web site.不带任何参数运行ws会将当前目录作为静态网站托管。 Navigating to the server will render a directory listing or your index.html , if that file exists.如果该文件存在,导航到服务器将呈现目录列表或您的index.html

$ ws
Listening on http://mbp.local:8000, http://127.0.0.1:8000, http://192.168.0.100:8000

Static files tutorial . 静态文件教程

This clip demonstrates static hosting plus a couple of log output formats - dev and stats .此剪辑演示了静态托管以及几种日志输出格式 - devstats

Single Page Application单页应用程序

Serving a Single Page Application (an app with client-side routing, eg a React or Angular app) is as trivial as specifying the name of your single page:为单页应用程序(具有客户端路由的应用程序,例如 React 或 Angular 应用程序)提供服务就像指定单页的名称一样简单:

$ ws --spa index.html

With a static site, requests for typical SPA paths (eg /user/1 , /login ) would return 404 Not Found as a file at that location does not exist.对于静态站点,对典型 SPA 路径(例如/user/1/login )的请求将返回404 Not Found因为该位置的文件不存在。 However, by marking index.html as the SPA you create this rule:但是,通过将index.html标记为 SPA,您可以创建此规则:

If a static file is requested (eg /css/style.css ) then serve it, if not (eg /login ) then serve the specified SPA and handle the route client-side.如果请求静态文件(例如/css/style.css ),则提供它,如果没有(例如/login ),则提供指定的 SPA 并处理客户端的路由。

SPA tutorial . SPA 教程

URL rewriting and proxied requests URL 重写和代理请求

Another common use case is to forward certain requests to a remote server.另一个常见用例是将某些请求转发到远程服务器。

The following command proxies blog post requests from any path beginning with /posts/ to https://jsonplaceholder.typicode.com/posts/ .以下命令将博客帖子请求从以/posts/开头的任何路径代理到https://jsonplaceholder.typicode.com/posts/ For example, a request for /posts/1 would be proxied to https://jsonplaceholder.typicode.com/posts/1 .例如,对/posts/1的请求将被代理到https://jsonplaceholder.typicode.com/posts/1

$ ws --rewrite '/posts/(.*) -> https://jsonplaceholder.typicode.com/posts/$1'

Rewrite tutorial . 重写教程

This clip demonstrates the above plus use of --static.extensions to specify a default file extension and --verbose to monitor activity.此剪辑演示了上述加上使用--static.extensions指定默认文件扩展名和--verbose来监视活动。

HTTPS and HTTP2 HTTPS 和 HTTP2

For HTTPS or HTTP2, pass the --https or --http2 flags respectively.对于 HTTPS 或--http2分别传递--https--http2标志。 See the wiki for further configuration options and a guide on how to get the "green padlock" in your browser.有关更多配置选项和有关如何在浏览器中获取“绿色挂锁”的指南,请参阅 wiki

$ lws --http2
Listening at https://mba4.local:8000, https://127.0.0.1:8000, https://192.168.0.200:8000

Node.js webserver from scratch从零开始的 Node.js 网络服务器


No 3rd-party frameworks;没有第三方框架; Allows query string;允许查询字符串; Adds trailing slash;添加尾部斜线; Handles 404把手 404


Create a public_html subfolder and place all of your content in it.创建一个public_html子文件夹并将您的所有内容放入其中。


Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3要点: https : //gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3

var fs = require('fs');

require('http').createServer(function(request, response) {
  var path = 'public_html'+ request.url.slice(0,
      (request.url.indexOf('?')+1 || request.url.length+1) - 1);
      
  fs.stat(path, function(bad_path, path_stat) {
    if (bad_path) respond(404);
    else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
      response.setHeader('Location', path.slice(11)+'/');
      respond(301);
    } else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
          function(bad_file, file_content) {
      if (bad_file) respond(404);
      else respond(200, file_content);
    });
  });
 
  function respond(status, content) {
    response.statusCode = status;
    response.end(content);
  }
}).listen(80, function(){console.log('Server running on port 80...')});

This is one of the fastest solutions i use to quickly see web pages这是我用来快速查看网页的最快解决方案之一

sudo npm install ripple-emulator -g

From then on just enter the directory of your html files and run从那时起,只需输入 html 文件的目录并运行

ripple emulate

then change the device to Nexus 7 landscape.然后将设备更改为 Nexus 7 横向。

I can also recommend SugoiJS, it is very easy to set up and gives an option to start writing fast and has great features. 我也可以推荐SugoiJS,它很容易设置,并提供快速开始编写和具有强大功能的选项。

Take a look here to get started: http://demo.sugoijs.com/ , documentation: https://wiki.sugoijs.com/ 看看这里开始: http//demo.sugoijs.com/ ,文档: https//wiki.sugoijs.com/

It has request handling decorators, request policies and authorization policies decorators. 它有请求处理装饰器,请求策略和授权策略装饰器。

For example: 例如:

import {Controller,Response,HttpGet,RequestParam} from "@sugoi/server";
​
@Controller('/dashboard')
export class CoreController{
    constructor(){}
​
    @HttpGet("/:role")
    test(@RequestParam('role') role:string,
         @RequestHeader("role") headerRole:string){
        if(role === headerRole )
            return "authorized";
        else{
            throw new Error("unauthorized")
        }
    }
}

Is very easy with the tons of libraries presents today. 今天有大量的图书馆,很容易。 Answers here are functional. 这里的答案是功能性的。 If you want another version for start faster and simple 如果您想要更快更简单的另一个版本

Of course first install node.js. 当然先安装node.js. Later: 后来:

> # module with zero dependencies
> npm install -g @kawix/core@latest 
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static

Here the content of " https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js " (you don't need download it, i posted for understand how works behind) 这里的内容为“ https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js ”(你不需要下载它,我发布了解如何工作背后)

// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" 

// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'

var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)

var app = express() 
app.use(express.static(folder)) 
app.listen(8181)
console.log("Listening on 8181")

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

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