方法如下:
1、在cmd窗口下,直接輸入命令 node D:\node-demo\hello.js,然後回車
2、在cmd窗口下,輸入node空格,然後把hello.js文件拖進去,然後回車。
3、在cmd窗口下,進入hello.js所在的文件夾,輸入 “node hello.js”命令,然後回車
然後瀏覽器運行 http://127.0.0.1:8888/
創建一個應用
步驟一、引入 required 模塊
我們使用 require 指令來載入 http 模塊,並將實例化的 HTTP 賦值給變量 http,實例如下:
var http = require("http");
步驟二、創建服務器
接下來我們使用 http.createServer() 方法創建服務器,並使用 listen 方法綁定 8888 端口。 函數通過 request, response 參數來接收和響應數據。
實例如下,在你項目的根目錄下創建一個叫 server.js 的文件,並寫入以下代碼:
var http = require('http'); http.createServer(function (request, response) { // 發送 HTTP 頭部 // HTTP 狀態值: 200 : OK // 內容類型: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // 發送響應數據 "Hello World" response.end('Hello World\n'); }).listen(8888); // 終端打印如下信息 console.log('Server running at http://127.0.0.1:8888/');
以上代碼我們完成了一個可以工作的 HTTP 服務器。
使用 node 命令執行以上的代碼:
node server.js Server running at http://127.0.0.1:8888/