[英]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服務器的步驟
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.