How to run index.html using a server(for angularjs

2019-08-17 03:20发布

问题:

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.