http之Redirect

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 都会进行跳转。此时,就算服务端改变设置也是没有用的,浏览器还是会从缓存中读取。

转载于:https://juejin.im/post/5ba5a7e3f265da0aa94a0f73

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值