http方法+安裝軟件包+學(xué)會寫路由

http模塊

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

1、http.createServer()

  • 定義:

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

  • 處理請求

  • 處理響應(yīng)

  • 語法:

http.createServer({選項對象},監(jiān)聽函數(shù))
  • 選項對象:可選。是一個object,通過選項對象,傳入一些參數(shù)。

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

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

返回值

createServer() 方法返回一個Server對象。

示例:


2、server.listen()

定義

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

語法

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

返回值

返回服務(wù)器對象

示例


3、res.setHeader()

定義

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

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

語法

res.setHeader(name, value)
res.setHeader(響應(yīng)頭屬性名, 對應(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)頭信息。特點:

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

語法

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

返回值

返回一個響應(yīng)對象。以便進行鏈式調(diào)用。

示例


6、res.end()

定義

end()用于通知服務(wù)器響應(yīng)結(jié)束。該方法在響應(yīng)時必須調(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)對象[ServerResponse]
    // console.log(req);//請求對象[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)運行在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)運行在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)運行在http://localhost:3000');
})

Npm install

語法

npm install module-name   //簡寫安裝:npm i express  //刪除 :npm uni express 
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)

express寫路由開始

  • 查找模塊:登錄npmjs.com 查詢一個你要的第三方模塊
  • 安裝模塊
  • 引入模塊
  • 使用模塊
1.創(chuàng)建文件夾 myname,右擊點擊終端打開,運行打印index.js文件。
2.創(chuàng)建index.js文件
3.安裝(登錄npmjs.com 查詢一個你要的第三方模塊);
4.例如:npm i express 
詳細:node.js(軟件包管理器) install(安裝)express(表示)
-----------------
5.例如:npm init --yes 
//全自動
----------------
5.例如:pm uni express
詳細:刪除軟件
-----------------
6.例如:運行index.js

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

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

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