前端起本地服務


前端項目有http請求的時候直接打開文件頁面就無法正常打開,這時候就需要起本地服務了。

1、用Hbuild打開項目,選中入口文件,或者要打開的頁面,點擊 運行->運行到瀏覽器->選擇一個瀏覽器 

 

 

 

2、用node.js 的http-server開啟本地服務,

前提:下載了node.js 然后在vs code終端或者在powershell窗口中輸入命令

1)假如用vs code編輯,在終端中輸入命令 node -v 和npm -v檢查已安裝的版本信息

 

 

 加入沒有安裝就安裝node.js

官網地址: https://nodejs.org

2)下載http-server

輸入命令 npm install http-server -g

3)開啟服務

進入目標文件夾,然后在終端輸入 npm http-server -c-l

4)關閉服務  快捷鍵Ctrl + c 

 

3、用node腳本文件起服務

1)安裝node.js

2)寫一個js腳本文件,把這個文件放到最外層目錄下,然后在js腳本文件的目錄下打開powershell窗口,輸入命令 node http.js

 

 

 這個端口號就是腳本文件內寫的端口號

用自己的ip地址加端口號在家文件路徑作為地址就能打開文件

eg:    http://10.150.124.14:4000/mpos/mpos/h5/query.html

弊端就是如果地址輸入錯誤窗口命令就會失效,要重新輸入一遍命令。

 

附件:http.js腳本文件 PORT可以自定義

var PORT = 4000; //

var http = require('http');
var url = require('url');
var fs = require('fs');
var mine = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
};
var path = require('path');

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join(".", pathname);

    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM