2015-07-19 70 views
0

我正在設計我的第一個webapp,我已經寫了前端的重要部分,現在我想做一個非常簡單的後端開始實現一些功能。過去幾天,我儘可能多地學習有效的後端開發和其他各種事情,但我遇到了一個巨大的問題。我基本上不知道如何附加我的前端和我的後端(我想用nodejs)。如何本地主機與nodejs的webapp

所有我想要的是使用我的瀏覽器去localhost:8080,並自動看到我的前端的HTML文檔,然後在我的前端代碼中有應用程序與服務器通信(獲取json信息或指示服務器添加事情到數據庫或類似的東西)。

+0

您使用的快遞? –

+0

我還沒有開始,那會讓我想做什麼更容易嗎? – Roscode

+0

是的,它一定會讓你想做的事更容易;從添加不同的API路線到提供靜態文件。 –

回答

0

一旦你在你的系統中安裝了節點。

文件夾結構:

讓您的文件的公共文件夾中的應用程序文件夾

導航裏面您的應用程序文件夾中TerminalCommand Prompt

然後創建一個文件作爲package.json,並保持在它下面的代碼:

{ 

    "name" : "YourAppName", 
    "version" : "0.0.1", 
    "description" : "App description", 
    "dependencies" : { 
     "mime" : "~1.2.7" 
    } 
} 

然後回到終端並運行npm install

然後創建一個文件作爲server.js並且繼續跟隨代碼在它:

var http = require("http"); 
var fs = require("fs"); 
var path = require("path"); 
var mime = require("mime"); 
var cache = {}; 
function send404(responce){ 
    responce.writeHead(404,{"content-type":"text/plain"}); 
    responce.write("Error 404: resourse not found"); 
    responce.end() 
} 
function sendFile(responce,filePath,fileContents){ 
    responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))}); 
    responce.end(fileContents); 
} 
function serveStatic(responce,cache,abspath){ 
    if(cache[abspath]){ 
     sendFile(responce,abspath,cache[abspath]); 
    }else{ 
     fs.exists(abspath,function(exists){ 
      if(exists){ 
       fs.readFile(abspath,function(err,data){ 
        if(err){ 
         send404(responce); 
        }else{ 
         cache[abspath] = data; 
         sendFile(responce,abspath,data); 
        } 
       }) 
      }else{ 
       send404(responce) 
      } 
     }) 
    } 
} 
var server = http.createServer(function(request,responce){ 
    var filePath = false; 
    if(request.url == '/'){ 
     filePath = 'public/index.html'; 
    }else{ 
     filePath = 'public'+request.url; 
    } 
    var abspath = './'+filePath; 
    serveStatic(responce,cache,abspath); 
}) 
server.listen(8080,function(){ 
    console.log("server running on 3000"); 
}) 

**此代碼是爲了幫助您開始使用節點JS,爲了更好的理解去node documentation。請閱讀mime模塊,這裏使用它。

0

您可以使用Grunt和使用連接插件,創建一個簡單的服務器,足以開發純JS Web應用程序。

使用咕嚕基本上需要2個文件

  • package.json
  • Gruntfile.js

package.json定義由咕嚕運行所需要的依賴關係。在你的情況下,將包括

  • grunt
  • grunt-contrib-connect(用於建立服務器插件)`

它可能還包括根據您的要求額外的依賴。

Gruntfile.js定義依賴關係的配置。在你的情況下,應該如何設置服務器。如果您使用其他的grunt-contrib-connect插件,您也應該配置它們。

參考: