FiddlerScript学习一:改动Request或Response

本文介绍了使用FiddlerScript进行请求与响应修改的方法,包括请求头与响应头的增删改、请求转发等操作。并通过实例展示了如何实现特定场景的需求。

前两天因项目须要,简单看了一下FiddlerScript,功能挺强的。今天有时间细致看一下,做个笔记。

改动Request或Response

改动Request和Response要在FiddlerScript中的OnBeforeRequest和OnBeforeResponse函数中加入规则就可以。OnBeforeRequest函数是在每次请求之前调用。OnBeforeResponse函数是在每次响应之前调用。

1、加入请求头Header

 oSession.oRequest["NewHeaderName"] = "New header value";

2、删除Response的Header

 oSession.oResponse.headers.Remove("Set-Cookie");

3、将请求从一个页面转发到同一Server上的还有一页面

if (oSession.PathAndQuery=="/hello/hello.html") {
      oSession.PathAndQuery="/hello/index.html";
    }
注意:oSession.PathAndQuery的值为fiddler中session列表中的Url:


即图中红色标注出来的部分。图中黄色标注出来的部分有点特殊。host为Tunnel to ,url为还有一host。

查看该请求的Header为:


这样的特殊情况会在以下还有样例。

上面的样例,拦截请求地址为/hello/hello.html的请求,并将其转发到同样Server的/hello/index.html


4、将请求转发到同样port号的不同server(改动请求的Host)


if(oSession.HostnameIs("www.baidu.com")){
      oSession.hostname = "www.sina.com.cn";
}

 
  

这个样例是将发送到百度的请求转发到新浪。则会提示页面不存在。

这里仅仅是改变了host,并不改变后面的地址。因此。假设在新浪上不存在对应的页面。如以下图片所看到的:

假设我訪问的是例如以下地址:http://www.baidu.com/link?url=CQuVpjo9u9UQADcstwECPEmrziPMk5u5H9PlRN2TbWLkKZaxafVER2X8OEYzovr-yasX2Fwcgj0NANBtKVj0gN78jNJ3bXTmIsTeBk7hXem

则结果例如以下:(该页面实际是存在的,是百度搜索出来的结果页面,被fiddler转发到新浪。可是新浪上不存的此页面)

5、将请求转发到不同port号,不同Server

    if (oSession.host=="192.168.0.70:8080") {
      oSession.host="192.168.0.69:8020";
    }
这个样例是将发送到192.168.0.70:8080的请求转发到192.168.0.69:8020,这里仅仅是改变host。并不改变后面的请求地址。比如,做以上的规则后。我请求的是:

http://192.168.0.70:8080/hello/hello.html


而实际我项目部署到的是:192.168.0.69:8020

6、将全部请求从一个server转发到还有一个server,包含Https

    // Redirect traffic, including HTTPS tunnels
    if (oSession.HTTPMethodIs("CONNECT") && (oSession.PathAndQuery == "www.example.com:443")) { 
        oSession.PathAndQuery = "beta.example.com:443"; 
    }

    if (oSession.HostnameIs("www.example.com")) oSession.hostname = "beta.example.com"; 

7、Simulate the Windows HOSTS file, by pointing one Hostname to a different IP address. (Retargets without changing the request's Host header)

    // All requests for subdomain.example.com should be directed to the development server at 128.123.133.123
    if (oSession.HostnameIs("subdomain.example.com")){
    oSession.bypassGateway = true;                   // Prevent this request from going through an upstream proxy
    oSession["x-overrideHost"] = "128.123.133.123";  // DNS name or IP address of target server
    }

8、Retarget requests for a single page to a different page, potentially on a different server. (Retargets by changing the request's Host header)

    if (oSession.url=="www.example.com/live.js") {
      oSession.url = "dev.example.com/workinprogress.js";
    }
9、Prevent upload of HTTP Cookies

 oSession.oRequest.headers.Remove("Cookie");

10、Decompress and unchunk a HTTP response, updating headers if needed

    // Remove any compression or chunking from the response in order to make it easier to manipulate
    oSession.utilDecodeResponse();

11、Search and replace in HTML.

    if (oSession.HostnameIs("www.bayden.com") && oSession.oResponse.headers.ExistsAndContains("Content-Type","text/html")){
      oSession.utilDecodeResponse();
      oSession.utilReplaceInResponse('<b>','<u>');
    }

12、Case insensitive Search of response HTML.

    if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "text/html") && oSession.utilFindInResponse("searchfor", false)>-1){
      oSession["ui-color"] = "red";
    }

13、Remove all DIV tags (and content inside the DIV tag)

    // If content-type is HTML, then remove all DIV tags
    if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html")){
      // Remove any compression or chunking
      oSession.utilDecodeResponse();
      var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);

      // Replace all instances of the DIV tag with an empty string
      var oRegEx = /<div[^>]*>(.*?

)<\/div>/gi; oBody = oBody.replace(oRegEx, ""); // Set the response body to the div-less string oSession.utilSetResponseBody(oBody); }


14、Pretend your browser is the GoogleBot webcrawler

oSession.oRequest["User-Agent"]="Googlebot/2.X (+http://www.googlebot.com/bot.html)";

15、Request Hebrew content

    oSession.oRequest["Accept-Language"]="he";

16、Deny .CSS requests

    if (oSession.uriContains(".css")){
     oSession["ui-color"]="orange"; 
     oSession["ui-bold"]="true";
     oSession.oRequest.FailSession(404, "Blocked", "Fiddler blocked CSS file");
    }

17、Simulate HTTP Basic authentication (Requires user to enter a password before displaying web content.)

    if ((oSession.HostnameIs("www.example.com")) && 
     !oSession.oRequest.headers.Exists("Authorization")) 
    {
    // Prevent IE's "Friendly Errors Messages" from hiding the error message by making response body longer than 512 chars.
    var oBody = "<html><body>[Fiddler] Authentication Required.<BR>".PadRight(512, ' ') + "</body></html>";
    oSession.utilSetResponseBody(oBody); 
    // Build up the headers
    oSession.oResponse.headers.HTTPResponseCode = 401;
    oSession.oResponse.headers.HTTPResponseStatus = "401 Auth Required";
    oSession.oResponse["WWW-Authenticate"] = "Basic realm=\"Fiddler (just hit Ok)\"";
    oResponse.headers.Add("Content-Type", "text/html");
    }
18、Respond to a request with a file loaded from the \Captures\Responses folder (Can be placed in OnBeforeRequest or OnBeforeResponse function)

    if (oSession.PathAndQuery=="/version1.css") {
      oSession["x-replywithfile"] ="version2.css";
    }


以上样例我并没有都实践。仅仅实践了中间几个地址转发的,由于如今须要用。剩下的请大家有须要的自己实践吧。



转载于:https://www.cnblogs.com/yfceshi/p/6819824.html

<template> <view class="container"> <!-- 顶部信息展示 --> <view class="header"> <view class="title">{{ formData.dcWjTitle }}</view> <view class="info"> <text>被测评人员:{{ formData.dcName }}</text> <text style="margin-left: 20rpx;">部门:{{ formData.dcDept }}</text> </view> </view> <!-- 其他页面内容 --> </view> </template> <script> export default { data() { return { formData: { dcWjTitle: '加载中...', dcName: '加载中...', dcDept: '加载中...' }, token: '' } }, onLoad(options) { const wjId = options.id console.log('接收到的问卷ID:', wjId) this.getTokenAndLoadData(wjId) }, methods: { async getTokenAndLoadData(id) { try { this.token = uni.getStorageSync('token') if (!this.token) { throw new Error('未找到认证令牌,请重新登录') } await this.loadQuestionnaireData(id) } catch (error) { console.error('获取token失败:', error) uni.showToast({ title: error.message || '请先登录', icon: 'none', duration: 3000 }) setTimeout(() => { uni.reLaunch({ url: '/pages/login/login' }) }, 1500) } }, async loadQuestionnaireData(id) { try { console.log('开始请求问卷数据,ID:', id) // 修复1: 使用正确的URL路径 const response = await uni.request({ url: `http://172.26.26.43/dev-api/wjdc/wj/${id}`, // 注意路径大小写 method: 'GET', header: { 'Authorization': `Bearer ${this.token}` }, timeout: 10000 // 添加超时设置 }) // 修复2: 正确处理uni.request返回结构 const [error, result] = response; if (error) { console.error('请求错误:', error) throw new Error(`网络请求失败: ${error.errMsg}`) } // 修复3: 检查状态码和业务码 if (result.statusCode !== 200) { throw new Error(`服务器返回错误状态: ${result.statusCode}`) } // 修复4: 根据接口格式获取数据 const responseData = result.data; if (responseData.code !== 200) { throw new Error(`接口错误: ${responseData.msg || '未知错误'}`) } // 修复5: 正确提取数据 const data = responseData.data console.log('接口返回数据:', data) // 更新表单数据 - 使用实际字段名 this.formData = { dcWjTitle: data.dcWjTitle || '无标题', dcName: data.dcName || '未知人员', dcDept: data.dcDept || '未知部门' } } catch (error) { console.error('请求失败:', error) // 显示错误信息 uni.showToast({ title: error.message || '数据加载失败', icon: 'none', duration: 3000 }) // 更新为错误状态 this.formData = { dcWjTitle: '数据加载失败', dcName: error.message || '请检查网络', dcDept: '联系管理员' } // 认证错误处理 if (error.message.includes('401') || error.message.includes('认证')) { uni.removeStorageSync('token') setTimeout(() => { uni.reLaunch({ url: '/pages/login/login' }) }, 1500) } } } } } </script> <style scoped> .container { padding: 20rpx; } .header { padding: 30rpx; background-color: #f8f8f8; border-radius: 12rpx; box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1); margin-bottom: 30rpx; } .title { font-size: 36rpx; font-weight: bold; margin-bottom: 20rpx; color: #333; text-align: center; } .info { display: flex; justify-content: center; font-size: 28rpx; color: #666; } .info text { margin: 0 10rpx; padding: 5rpx 15rpx; background-color: #eef7ff; border-radius: 8rpx; } </style> 报错:17:26:02.824 请求失败:, TypeError: response is not iterable at pages/operation/operation.vue:103
最新发布
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值