http之Redirect

littlebirdflying發表於2018-09-22

Redirect 的概念

通過 url 訪問某個路徑請求資源時,發現資源不在 url 所指定的位置,這時伺服器要告訴瀏覽器,新的資源地址,瀏覽器再重新請求新的 url,從而拿到資源。

若伺服器指定了某個資源的地址,現在需要更換地址,不應該立刻廢棄掉 url,如果廢棄掉可能直接返回 404,這時應該告訴客戶端新的資源地址。

Redirect 的使用

啟動伺服器 node server.js,localhost:8888 訪問

訪問時,發現 url 變成了 localhost:8888/new 了,並顯示了 /new 路由下的內容

// server.js
const http = require('http')

http.createServer(function (request, response) {
  console.log('request come', request.url)

  if (request.url === '/') {
    response.writeHead(302, {  // or 301
      'Location': '/new' // 這裡是同域跳轉,只需要寫路由
    })
    response.end()
  }
  if (request.url === '/new') {
    response.writeHead(200, {
      'Content-Type': 'text/html',
    })
    response.end('<div>this is content</div>')
  }
}).listen(8888)

console.log('server listening on 8888')
複製程式碼

檢視network localhost

請求發現是302後,瀏覽器自動根據響應頭中的 Location 路徑進行跳轉。

General
Status Code: 302 Found (from disk cache)

Request Headers
Location: /new
複製程式碼

Redirect 301 和 302 的區別

302 臨時跳轉,每次請求仍然需要經過服務端指定跳轉地址

301 永久跳轉

301的情況

每次訪問 locahost:8888,都要經過服務端跳轉,服務端通過 console.log 可以看到 / /new 兩次請求。

const http = require('http')

http.createServer(function (request, response) {
  console.log('request come', request.url)

  if (request.url === '/') {
    response.writeHead(302, {  
      'Location': '/new' 
    })
    response.end()
  }
  if (request.url === '/new') {
    response.writeHead(200, {
      'Content-Type': 'text/html',
    })
    response.end('<div>this is content</div>')
  }
}).listen(8888)

console.log('server listening on 8888')
複製程式碼

301 的情況

訪問 locahost:8888,第一次經過服務端跳轉,服務端通過 console.log 可以看到 / /new 兩次請求;第二次 服務端 console.log 只顯示 /new ,沒有再次經過伺服器指定新的 Location

response.writeHead(301, {
      'Location': '/new'
    })
複製程式碼

注意:使用 301 要慎重,一旦使用,服務端更改路由設定,使用者如果不清理瀏覽器快取,就會一直重定向。

設定了 301,locahost 會從快取中讀取,並且這個快取會保留到瀏覽器,當我們訪問 8888 都會進行跳轉。此時,就算服務端改變設定也是沒有用的,瀏覽器還是會從快取中讀取。

http之Redirect

相關文章