res.end()
res.end是不允許輸出多行的
此時我們多復制幾個進行輸出
var http = require("http"); // 得到內置模塊,引入NodeJS的內置http模塊 // 創建服務器,使用createServer方法 // createServer方法中有一個回調函數,req參數表示的是請求,res的參數表示的是響應 var server = http.createServer(function(req,res){ res.end("Hello world"); // 輸出 res.end("Hello world"); // 輸出 res.end("Hello world"); // 輸出 res.end("Hello world"); // 輸出 res.end("Hello world"); // 輸出 res.end("Hello world"); // 輸出 }) // 監聽,默認的端口是80(Apache),所以我們用3000端口 server.listen(3000,function(){ console.log("監聽3000端口") })
瀏覽器中只輸出一行結果
res.end也不能輸入非字符串
此時我們輸出一個數字就回報錯,查看報錯信息,提醒我們不能輸出number類型
res.end是可以結合HTML標簽顯示的
res.end("<h1>hello world</h1>"); // 輸出
res.write()
如果要使用res.write最后必須要有res.end,否則瀏覽器處於請求狀態
多條語句輸出使用的是res.write,並且也結合HTML標簽進行使用
var http = require("http"); // 得到內置模塊,引入NodeJS的內置http模塊 // 創建服務器,使用createServer方法 // createServer方法中有一個回調函數,req參數表示的是請求,res的參數表示的是響應 var server = http.createServer(function(req,res){ res.write("<p>hello world</p>"); // 輸出 res.write("<p>hello world</p>"); // 輸出 res.write("<p>hello world</p>"); // 輸出 res.end("輸出完畢") }) // 監聽,默認的端口是80(Apache),所以我們用3000端口 server.listen(3000,function(){ console.log("監聽3000端口") })
此時我們看到瀏覽器會輸出
此時出現亂碼是因為我們沒喲設置字符集
res.setHeader("Content-type","text/html;charset=utf8");
設置字符集之后查看
如果此時我們沒有res.end(),我們會看到瀏覽器會一直處於請求狀態
和res.end一樣不能輸入非字符串的內容