http模塊

http模塊

  • http模塊是Node的內(nèi)置模塊。
  • http模塊用于構(gòu)建服務(wù)器。

1.http.createServer()

定義

用于創(chuàng)建一個(gè)Node服務(wù)器。主要做了兩件事:

  • 處理請(qǐng)求
  • 處理響應(yīng)

語法

http.createServer({選項(xiàng)對(duì)象},監(jiān)聽函數(shù))

選項(xiàng)對(duì)象:可選。是一個(gè)object,通過選項(xiàng)對(duì)象,傳入一些參數(shù)。

監(jiān)聽函數(shù):是一個(gè)回調(diào)函數(shù)。當(dāng)用戶請(qǐng)求從端口進(jìn)來后,該函數(shù)立刻被調(diào)用。

  • Request對(duì)象:請(qǐng)求對(duì)象
    • 請(qǐng)求對(duì)象:包含與請(qǐng)求有關(guān)信息。
  • Response對(duì)象:響應(yīng)對(duì)象
    • 響應(yīng)對(duì)象:包含與響應(yīng)有關(guān)的信息。

返回值

createServer() 方法返回一個(gè)Server對(duì)象。

示例:


2.server.listen()

定義

用于監(jiān)聽服務(wù)器端口。

語法

server.listen()
server.listen([port[,host][,callback])
server.listen(端口,主機(jī)名,回調(diào)函數(shù))
  • 端口: 數(shù)值
  • 主機(jī)名:字符串
  • 連接數(shù):數(shù)值(最大511)
  • 回調(diào)函數(shù):function

返回值

返回服務(wù)器對(duì)象

示例

3.res.setHeader()

定義

用于設(shè)置響應(yīng)頭信息。特點(diǎn):

  • 只能設(shè)置一個(gè)值
  • 多次執(zhí)行
  • 優(yōu)先級(jí)低于res.writeHead()

語法

res.setHeader(name, value)
res.setHeader(響應(yīng)頭屬性名, 對(duì)應(yīng)的值)

返回值

示例

res.setHeader("Content-Type","text/html")
res.setHeader("Content-Type","text/plain")
res.setHeader("Content-Type", "application/json")

4.res.write()

定義

write()方法用于設(shè)置響應(yīng)數(shù)據(jù)。

語法

response.write(chunk[, encoding][, callback]);
response.write(數(shù)據(jù)[,字符編碼][, 回調(diào)函數(shù)]);

返回值

布爾值

示例


5.res.writeHead()

定義

用于設(shè)置響應(yīng)頭信息。特點(diǎn):

  • 設(shè)置多個(gè)值
  • 只能執(zhí)行一次
  • 優(yōu)先級(jí)高于res.setHeader()

語法

res.writeHead(statusCode[, statusMessage][, headers]);
res.writeHead(狀態(tài)碼,'狀態(tài)信息',{響應(yīng)頭});

返回值

返回一個(gè)響應(yīng)對(duì)象。以便進(jìn)行鏈?zhǔn)秸{(diào)用。

示例


6.res.end()

定義

end()用于通知服務(wù)器響應(yīng)結(jié)束。該方法在響應(yīng)時(shí)必須調(diào)用。

語法

response.end([data[, encoding]][, callback])
res.end('數(shù)據(jù)','字符編碼',回調(diào)函數(shù))

返回值

返回this

示例


讀取文件內(nèi)容

const http = require('node:http')
const fs = require('fs')

const server = http.createServer((req,res) => {
    // console.log(res);//響應(yīng)對(duì)象[ServerResponse]
    // console.log(req);//請(qǐng)求對(duì)象[inComingMessage]
    console.log(req.url);
    //設(shè)置響應(yīng)頭的數(shù)據(jù)類型
    // res.setHeader('Content-Type', 'text/html;charset=utf-8')
    // res.write('<h1>你好世界</h1>')
    // res.write('<h2>你好中國</h2>')
    // res.end()

    //讀取index.html內(nèi)容作為響應(yīng)數(shù)據(jù)
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    fs.readFile('./views/index.html',(err,data) => {  
        if(err){
            console.log(err);
            res.end()
        } else {
            res.end(data)//把數(shù)據(jù)寫在這里
        }
    })
    
})

server.listen(3000,'localhost',511,() => {
    console.log('服務(wù)器已經(jīng)運(yùn)行在http://localhost:3000');
})

添加路由

const http = require('node:http')
const fs = require('fs')

const server = http.createServer((req,res) => {
    console.log(req.url);
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
  //添加路由
    //條件判斷 path  = './views/index.html'
     
    // fs.readFile('./views/index.html',(err,data) => {
    // fs.readFile('./views/about.html',(err,data) => {
    fs.readFile('./views/404.html',(err,data) => {
        if(err){
            console.log(err);
            res.end()
        } else {
            res.end(data)//把數(shù)據(jù)寫在這里
        }
    })
    
})

server.listen(3000,'localhost',511,() => {
    console.log('服務(wù)器已經(jīng)運(yùn)行在http://localhost:3000');
})

熟練掌握node.js路由的原生寫法

const http = require('node:http')
const fs = require('fs')

const server = http.createServer((req, res) => {
    console.log(req.url);
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    //////////////添加路由:router/////////////////
    //條件判斷 path  = './views/index.html'
    let path = './views/'
    switch (req.url) {
        case '/':
            path += 'index.html'
            res.statusCode = 200
            break
        case '/about':
            path += 'about.html'
            res.statusCode = 200
            break
        case '/about-me':
            res.setHeader('Location', '/about')
            res.statusCode = 301
            break
        default:
            path += '404.html'
            res.statusCode = 404
    }
    // fs.readFile('./views/index.html',(err,data) => {
    // fs.readFile('./views/about.html',(err,data) => {
    fs.readFile(path, (err, data) => {
        if (err) {
            console.log(err);
            res.end()
        } else {
            res.end(data)//把數(shù)據(jù)寫在這里
        }
    })

})

server.listen(3000, 'localhost', 511, () => {
    console.log('服務(wù)器已經(jīng)運(yùn)行在http://localhost:3000');
})

Npm install

語法

npm install module-name
npm install -g module-name # -g:全局安裝
npm i module-name  # npm i是npm install的別名
npm install module-name --save
npm install module-name --not--save
npm install module-name --save-dev

express寫路由

const express = require('express')
const app = express()

app.get('/', function (req, res) {
    // res.send('Hello World')
    res.sendFile('./views/index.html',{root:__dirname})
})
app.get('/about', function (req, res) {
    res.sendFile('./views/about.html',{root:__dirname})
})
app.get('/about-me', function (req, res) {
    res.redirect('/about')
})

//404 page
app.use((req,res) => {
    res.status(404).sendFile('./views/404.html',{root:__dirname})
})

app.listen(3000)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容