前端起本地服务

前端项目有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 + ".");

猜你喜欢

转载自www.cnblogs.com/yuexiadeyang/p/12420863.html