繁体   English   中英

我可以将Node用作HTML应用程序的Web服务器吗?

[英]Can i use node as webserver for html app?

很抱歉问这样一个简单的问题。 我已经被某人发送了一个文件,一个index.html文件,该文件在script标签内插入一个js文件。 我必须启动一个Web服务器以通过身份验证并查看文件(在开发中是上午)。

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

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

设置节点Web服务器的步骤

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

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>

转到项目根路径,并显示命令提示符,然后通过运行命令节点server.js启动服务器。

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

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

是的,这是可能的。

一个简单的例子就是创建文件,将其命名为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软件包可以帮助您完成此任务,但这是从字面上读取index.html并将其作为响应返回的最简单的“纯节点”示例。

由于您不想构建后端,而只是构建http服务器。 我建议使用npm软件包,该软件包可以满足您的需求:

打开控制台

npm install http-server -g

转到控制台中的“ index.html”文件夹,然后键入:

http-server

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

http://localhost:8080

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

使用节点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

这是参考

这样甚至可以解决您的反斜杠问题

暂无
暂无

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

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