我可以将节点用作html应用程序的网络服务器吗?

时间:2018-04-10 09:58:40

标签: node.js

我很抱歉提出这么简单的问题。我已经被某人发送了文件,这是一个index.html文件,它在script个标签中提取了一个js文件。我必须启动一个Web服务器来完成身份验证并查看文件(我在开发中)。

在我的CLI中,我已导航到包含index.html的目录。我已经使用node -v检查了我是否全局安装了它(是的,v 8.6)。我运行了简单的命令node并在http://localhost:3000和其他一些端口检查了我的浏览器,但没有得到任何乐趣。我也试过node index.html但是CLI会抛出错误。

如何启动网络服务器?在线的所有示例都告诉我要构建一个.js文件,但这不是一个选项。

4 个答案:

答案 0 :(得分:3)

设置节点网络服务器的步骤

  1. 从本地计算机创建路径文件夹。
  2. 从项目根路径转到命令提示符。
  3. 使用 npm install express
  4. 命令安装express
  5. 创建 server.js 文件
  6. 创建文件夹 wwww 并在其中创建 Index.html
  7. <强> server.js

    var express = require('express');
    var app = express();
    
    app.use(express.static(__dirname + '/www'));
    
    app.listen('3000');
    console.log('working on 3000');
    

    <强>的index.html

    <!doctype html
    <html> 
    <head> 
    <title> my local server </title> 
    </head>
    <body>
    <h1> server working </h1>
    <p> just put your html,css, js files here and it work on your own local nodejs server </p>
    </body>
    </html>
    

    转到项目根路径并执行命令提示符,然后通过运行命令 node server.js

    启动服务器

    然后转到浏览器并运行网址 localhost:3000

    现在您可以看到html页面将在您的浏览器上呈现。

答案 1 :(得分:1)

是的,这是可能的。

如何执行此操作的一个非常简单的示例是创建文件,让我们将其称为app.js并将其放入其中:

const http = require('http'),   // to listen to http requests
      fs = require('fs');       // to read from the filesystem

const app = http.createServer((req,res) => {
    // status should be 'ok'
    res.writeHead(200); 

    // read index.html from the filesystem, 
    // and return in the body of the response
    res.end(fs.readFileSync("index.html")); 
});

app.listen(3000); // listen on 3000

现在,运行node app.js

浏览至http://localhost:3000

有大量其他npm软件包可以帮助你做到这一点,但这是最简单的纯粹节点&#39;示例来读取index.html并将其作为响应提供回来。

答案 2 :(得分:1)

因为您不想构建后端而只是构建http服务器。 我建议使用一个能满足你需要的npm包:

打开控制台

npm install http-server -g

转到“index.html”文件夹(在控制台中),然后输入:

http-server

然后在您的浏览器中通过以下地址访问您的内容:

http://localhost:8080

此处的文档: https://www.npmjs.com/package/http-server

答案 3 :(得分:0)

使用节点js

启动服务器非常容易

创建server.js文件

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

http.createServer(function (req, res) {
  fs.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).listen(3000);

运行node server.js

Here is a reference

这甚至可以通过此

解决您的反斜杠问题
相关问题