- 其他編程語言竹习,需要借用Apache或者Nginx的HTTP的服務(wù)器來處理請求;但是nodejs完全不一樣列牺,直接引用http模塊就可以了
代碼也比較簡單
const http = require("http");
http.createServer(function(req,res){
//發(fā)送http頭部
//http狀態(tài)值:200 ok
// 設(shè)置http 頭部整陌,狀態(tài)碼是200,文件類型是html瞎领,字符集是utf8
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
res.write("你好");
//結(jié)束響應(yīng)
res.end();
}).listen(8001);
在控制臺啟動程序泌辫,node XXX.js
然后在瀏覽器:http://localhost:8081,頁面打印出“你好”
- URL模塊
該模塊其實(shí)就是對URL進(jìn)行一些操作九默,該模塊提供了方法可以方便獲取url的各種參數(shù)震放,也可以實(shí)現(xiàn)對url的操作。常用的就是parse方法驼修,方法使用如下:
const http = require("http");
const url = require("url");
http.createServer(function(req,res){
const result = url.parse("http://www.baidu.com?name=zhangsan&age=18",true);
console.log(result);
res.end();
}).listen(8001);
parse獲取的數(shù)據(jù)如下:
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?name=zhangsan&age=18',
query: { name: 'zhangsan', age: '18' },
pathname: '/',
path: '/?name=zhangsan&age=18',
href: 'http://www.baidu.com/?name=zhangsan&age=18' }
3.supervisor
不使用supervisor的話殿遂,每次修改nodejs的代碼都需要重新啟動诈铛。但是如果使用了supervisor,只需要啟動一次墨礁,后面修改代碼會自動刷新幢竹,不需要重啟。
npm install -g supervisor
// 啟動換成以下方式
supervisor nodejs文件
//之后改代碼會自動刷新