Redirect 重定向

Redirect 重定向

1.基本使用:

const http = require('http');  //用于创建 服务的 http模块
const fs = require('fs');  //用于读写文件的 模块标题
//使用 http 的 createServer 方法 创建 一个 服务   该方法 会返回 一个 新建的 http.Server 实例
http.createServer(function(request,response){  //回调 函数
    //一些 请求 的处理 和数据 的返回
    console.log('request start',request.url);

    if(request.url === '/index'){  //判断 若 请求 url 为 /test  则 进行 列 处理
        const html = fs.readFileSync('index.html','utf8'); // 同步读取  文件    并且 编码 为 utf-8

        /**此处还可以 进行 一些 其他的 操作   例如请求 限制  返回头 的 设置
         * **/
        response.writeHead(200,{
            'Content-Type':'text/html',
            'set-cookie':['abc=123;','bcd=456']
            // 'Content-Security-Policy':`default-src 'self';`
        });
        response.end(html);  //将 数据 发送 给 客户端
    }else if(request.url === '/'){
        response.writeHead(302,{
            'Location':'/index'
        });
        response.end();
    }else{
        const js = fs.readFileSync('index.js','utf8');
        response.writeHead(200,{
            'Content-Type':'application/javascript',
        });
        response.end(js); // response.end() 方法 接收一个 字符串 参数
    }
}).listen(8000,function(){
    console.log('service is on port 8000');
}); //监听8000端口

上述 代码 当 访问 localhost:8000/ 时 会自动 重定向 到 /index 页面
只需要在 响应 头 中 设置 Location 属性 指定 跳转到 的 新 路由 即可。

2.301与302区别:

  • 301: 资源 永久 移到别的 地方,当使用了301时 浏览器 会自动 缓存 久的 访问请求 数据,并且 该缓存 必须要 用户 手动 清除,才会清除。这会造成,当服务器修改了定向地址时,如果用户不清缓存,则永远都不会定向到新的地址,所以使用时 尽量使用 302代替
  • 302: 资源暂时 移到 别的 地方
发布了96 篇原创文章 · 获赞 64 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41709082/article/details/96166903