How to run index.html using a server(for angularjs and other frameworks)

你说的曾经没有我的故事 提交于 2020-01-16 07:41:30

问题


I have searched stackoverflow and some forums and couldn't find a direct solution and later I came across some ans which works fine so I'm posting it here :)

The ans is for the below folder structure and you can also customize it for your folder structure.

--project
---app
----js
----services
----(...)
----index.html

Please refer the answer below. Please post if you have better way to do it and also you can add some comments to make the answer better. Thanks.


回答1:


Method 1:

Using node.js to run index.html file copy paste the below code to server.js file in your app folder(above hierarchy)

var http = require('http');
var fs = require("fs");

http.createServer(function(request, response) {
  if(/(.*?).css$/.test(request.url.toString())){
     sendFileContent(response, request.url.toString().substring(1), "text/css");
  }else if(/(.*?).js$/.test(request.url.toString())){
    sendFileContent(response, request.url.toString().substring(1), "text/javascript");
  }else if(/(.*?).html$/.test(request.url.toString())){
    sendFileContent(response, request.url.toString().substring(1), "text/html");
  }else if(request.url.toString().substring(1) == ''){
    sendFileContent(response, "index.html", "text/html");
  }
}).listen(3000);

function sendFileContent(response, fileName, contentType){
  fs.readFile(fileName, function(err, data){
    if(err){
      response.writeHead(404);
      response.write("Not Found!");
    }
    else{
      response.writeHead(200, {'Content-Type': contentType});
      response.write(data);
    }
    response.end();
  });
}

and from the app folder run node server.js. Your html file will be serving in localhost:3000


Method 2:

Using http-server. Follow the steps in this link to install http-server globally and from your app folder run cmd http-server -a localhost -p 8000 -c-1 ./app

and your index.html file will be serving in localhost:8000

Note: You can change the port number in .listen and -p in above methods.



来源:https://stackoverflow.com/questions/50059983/how-to-run-index-html-using-a-serverfor-angularjs-and-other-frameworks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!