让你明明白白学知识,有代码,有讲解,抄的走,学的会!
我们某些应用场景,可能需要进行页面重定向,重定向又2种
- 301 永久重定向
- 302 临时重定向
express中有语法糖,直接使用
a链接触发重定向
app.js
const express = require('express')
const app = express()
const router = express.Router()
// 演示通过页面跳转的方式进行重定向,无需前端操作
router.get('/api/passToPageRedirect', (req, res) => {
// 这里的 res.redirect(响应状态码可以是301,302, 要重定向的地址)
res.redirect(302, 'http://localhost:3000/liuyan.html')
res.end()
})
app.listen(3000, ()=> {
console.log('http://localhost:3000')
})
这种情况的前端代码必须是下面这样
<a href="/api/passToPageRedirect">跳转</a>
<form action="/api/passToPageRedirect" method="get">
<button type='submit'>表单触发页面跳转</button>
</form>
a链接和 表单的提交,触发的默认行为,都会刷新页面,都能进行重定向操作
在触发301或者 302重定向以后,页面刷新,控制台中的 network面板中,可以看到请求的过程


通过接口触发重定向
如果调用GET、或者POST接口,然后后台进行重定向操作,其实express只会给你在响应头加一个Location字段,前端必须拿到Location 然后,自己通过 window.location.href = Location地址 跳转
app.js
const express = require('express')
const app = express()
const router = express.Router()
// 使用Location进行重定向
router.get('/api/passToAPIRedirect', (req, res) => {
res.location('http://localhost:3000/liuyan.html')
res.end()
})
app.listen(3000, ()=> {
console.log('http://localhost:3000')
})
前端代码
<script src="/plugins/jquery.js"></script>
<script>
$.ajax({
url: '/api/passToAPIRedirect',
success(res, stauts, xhr) {
console.log(xhr.getAllResponseHeaders())
window.location.href = xhr.getResponseHeader('Location')
},
error(err) {
console.log(err)
}
})
</script>
在success响应函数体内,我们可以获取到服务器返回的响应头部添加的属性 Location

使用window.location.href=Location地址 手动调用一下,我们是不会在看到跳转以后的liuyan.html页面的控制台看到 /api/passToAPIRedirect 接口的详细信息,因为已经没了,页面刷新了
无论是哪一种方式,都是可以实现重定向,但是上面的方式,使用时一定不能用错位使用, 因为express并不会控制页面如何跳转,最终跳转还是依赖前端自己控制
总结:
- 使用 301、302重定向,要页面自己使用a,form表单 触发默认行为
- 使用location手动进行页面跳转,需要前端自己获取响应头中的Location字段值,然后调用 window.location.href 跳转
- 2种方式,在控制台中看到的效果是不同的,window.location.href在跳转以后,看不到请求接口的详细信息, 301,302的依旧可以在liuyan.html目标页面中看的到信息