修改响应头

更新时间:2025-04-27 06:35:24

修改响应头适用于内容优化与缓存控制、安全增强、性能优化等场景。本文使用一个简单的修改响应头使用示例,帮助您快速了解修改响应头功能的作用。

代码示例

  • 实现效果:当客户端向边缘函数发起请求时,边缘函数会代替客户端去请求第三方网站,获取到响应后,对响应头进行一系列的自定义操作如添加、删除、修改,然后将修改后的响应返回给客户端。

  • 语言类型Javascript

  • 代码示例

    /**
     * 本示例为边缘函数获取第三方网站资源后,修改响应头并返回客户端
     * 测试时请将 url 替换为您自己的地址
     */
    // 定义要请求的第三方网站的 URL
    const url = "https://aliyun.com"
    
    // 定义一个异步函数 handleRequest,用于处理请求
    async function handleRequest(request) {
      // 使用 fetch 函数发起对第三方网站的请求,并获取响应
      const response = await fetch(url)
    
      // 创建一个新的 Response 对象,仅复制返回内容的 body 部分
      // 这里将 response.body 作为新响应的主体,同时保留原有的响应状态和头信息
      const newResponse = new Response(response.body, response)
    
      // 自定义增加一个新的响应头 "custom-ER-add",值为 "ER header"
      newResponse.headers.append("custom-ER-add", "ER header")
    
      // 自定义删除一个名为 "custom-ER-delete" 的响应头
      newResponse.headers.delete("custom-ER-delete")
    
      // 自定义修改一个名为 "custom-ER-reset" 的响应头,将其值设置为 "ER header"
      newResponse.headers.set("custom-ER-reset", "ER header")
    
      // 返回修改后的响应
      return newResponse
    }
    
    // 导出默认的 fetch 函数,这是边缘函数的标准接口
    export default {
      fetch(request) {
        // 调用 handleRequest 函数处理请求
        return handleRequest(request)
      }
    }

部署效果

  • 客户端原响应头

    以如下客户端响应头为例,在此响应头基础上进行新增、删除及修改操作。

    # 客户端原响应头
    # 响应的内容类型为HTML文档,字符编码为UTF-8
    Content-Type: text/html; charset=UTF-8
    # 响应体的长度为1234字节
    Content-Length: 1234
    # 服务器软件为Apache
    Server: Apache
    # 自定义响应头字段,值为"original-value",可能会被删除
    custom-ER-delete: original-value
    # 自定义响应头字段,值为"original-value",可能会被修改
    custom-ER-reset: original-value
  • 修改响应头

    • 新增custom-ER-add字段

      在原响应头中新增custom-ER-add字段。

      Content-Type: text/html; charset=UTF-8
      Content-Length: 1234
      Server: Apache
      custom-ER-delete: original-value
      custom-ER-reset: original-value
      custom-ER-add: ER header
    • 删除custom-ER-delete字段

      在新增操作后的响应头中删除custom-ER-delete字段。

      Content-Type: text/html; charset=UTF-8
      Content-Length: 1234
      Server: Apache
      custom-ER-reset: original-value
      custom-ER-add: ER header
    • 修改custom-ER-reset字段

      在删除操作后修改custom-ER-reset字段。

      Content-Type: text/html; charset=UTF-8
      Content-Length: 1234
      Server: Apache
      custom-ER-add: ER header
      custom-ER-reset: ER header
  • 客户端接收响应头

    Content-Type: text/html; charset=UTF-8
    Content-Length: 1234
    Server: Apache
    custom-ER-add: ER header
    custom-ER-reset: ER header
  • 本页导读
  • 代码示例
  • 部署效果
AI助理

点击开启售前

在线咨询服务

你好,我是AI助理

可以解答问题、推荐解决方案等