AnyProxy 修改requestData(JSON)

github上的demo

直接返回了一个自定义的 'i-am-anyproxy-modified-post-data'

module.exports = {
  summary: 'Rule to modify request data',
  *beforeSendRequest(requestDetail) {
    if (requestDetail.url.indexOf('http://httpbin.org/post') === 0) {
      return {
        requestData: 'i-am-anyproxy-modified-post-data'
      };
    }
  },
};

现实中,我通常是需要针对原有的请求data做一部分的修改,例如在请求json中,增加一个新的key:value

操作步骤:

1.Buffer数据 toString()成普通字符串

2.将字符串转换成jsonObect

3.针对jsonObject操作,增 删 改 key:value值

4.将修改后的jsonObject toString成字符串,直接做接口返回(requestData:新改后的json字符串) 

参考如下代码(modify_request_data.js):

module.exports = {
  summary: 'Rule to modify request data',
  *beforeSendRequest(requestDetail) {
    console.log('已经进入拦截')
    
 if (requestDetail.url.endsWith('/api/shop/front/trcOrder/submitOrder') || 
        requestDetail.url.endsWith('/api/loan/front/loan-application') ) {

      json = requestDetail.requestData.toString()
      console.log("请求前json+++++++++++start++++++++++++++++++++++++++++++++++++")
      console.log(json)
      console.log("请求前json+++++++++++end++++++++++++++++++++++++++++++++++++++")
      json_obj = JSON.parse(json)
      //修改请求参数,增加"remark"="nancyaddvalue"这个key:value值
      json_obj["remark"]="nancyaddvalue"
      console.log("修改请求data的json+++++++++++start++++++++++++++++++++++++++++++++++++")
      console.log(json_obj)
      console.log("修改请求data的json+++++++++++end++++++++++++++++++++++++++++++++++++++")
      return {
        //返回的requestData不需要buffer形式,string类型即可
        requestData: JSON.stringify(json_obj)
      };
    }
  },
};

执行 anyproxy -i --rule modify_request_data.js

发起请求,结果如下

[AnyProxy Log][2018-10-12 19:12:03]: received request to: POST 10.10.10.10:81/api/shop/front/trcOrder/submitOrder
已经进入拦截
请求前json+++++++++++start++++++++++++++++++++++++++++++++++++
{"OrderNo":"1234","period":12}
请求前json+++++++++++end++++++++++++++++++++++++++++++++++++++
修改请求data的json+++++++++++start++++++++++++++++++++++++++++++++++++
{ shopOrderNo: '1234',
  period: 12,
  remark: 'nancyaddvalue' }
修改请求data的json+++++++++++end++++++++++++++++++++++++++++++++++++++

 

 

requestDetail的结构,可以看出requestDetail.requestData 的类型是Buffer

{
	requestOptions: {
		hostname: '10.10.10.10',
		port: '81',
		path: '/api/shop/front/trcOrder/submitOrder',
		method: 'GET',
		headers: {
			Host: '10.10.10.10:81',
			'DingTalk-Flag': '1',
			'Proxy-Connection': 'keep-alive',
			'Upgrade-Insecure-Requests': '1',
			Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77 AliApp(DingTalk/4.5.11) com.laiwang.DingTalk/10450412 Channel/201200 language/zh-Hans-CN',
			'Accept-Language': 'zh-cn',
			'Accept-Encoding': 'gzip, deflate',
			Connection: 'keep-alive'
		}
	},
	protocol: 'http',
	url: 'http://10.10.10.10:81/api/shop/front/trcOrder/submitOrder',
	requestData: < Buffer > ,
	_req: IncomingMessage {
		_readableState: ReadableState {
			objectMode: false,
			highWaterMark: 16384,
			buffer: [BufferList],
			length: 0,
			pipes: null,
			pipesCount: 0,
			flowing: true,
			ended: true,
			endEmitted: true,
			reading: false,
			sync: true,
			needReadable: false,
			emittedReadable: false,
			readableListening: false,
			resumeScheduled: false,
			destroyed: false,
			defaultEncoding: 'utf8',
			awaitDrain: 0,
			readingMore: false,
			decoder: null,
			encoding: null
		},
		readable: false,
		_events: {
			data: [Function],
			end: [Function]
		},
		_eventsCount: 2,
		_maxListeners: undefined,
		socket: Socket {
			connecting: false,
			_hadError: false,
			_handle: [TCP],
			_parent: null,
			_host: null,
			_readableState: [ReadableState],
			readable: true,
			_events: [Object],
			_eventsCount: 9,
			_maxListeners: undefined,
			_writableState: [WritableState],
			writable: true,
			allowHalfOpen: true,
			_bytesDispatched: 0,
			_sockname: null,
			_pendingData: null,
			_pendingEncoding: '',
			server: [Server],
			_server: [Server],
			_idleTimeout: 120000,
			_idleNext: [TimersList],
			_idlePrev: [TimersList],
			_idleStart: 274054,
			_destroyed: false,
			parser: [HTTPParser],
			on: [Function: socketOnWrap],
			_paused: false,
			_httpMessage: [ServerResponse],
			[Symbol(asyncId)]: 1450,
			[Symbol(lastWriteQueueSize)]: 0,
			[Symbol(bytesRead)]: 0,
			[Symbol(asyncId)]: 1452,
			[Symbol(triggerAsyncId)]: 1450
		},
		connection: Socket {
			connecting: false,
			_hadError: false,
			_handle: [TCP],
			_parent: null,
			_host: null,
			_readableState: [ReadableState],
			readable: true,
			_events: [Object],
			_eventsCount: 9,
			_maxListeners: undefined,
			_writableState: [WritableState],
			writable: true,
			allowHalfOpen: true,
			_bytesDispatched: 0,
			_sockname: null,
			_pendingData: null,
			_pendingEncoding: '',
			server: [Server],
			_server: [Server],
			_idleTimeout: 120000,
			_idleNext: [TimersList],
			_idlePrev: [TimersList],
			_idleStart: 274054,
			_destroyed: false,
			parser: [HTTPParser],
			on: [Function: socketOnWrap],
			_paused: false,
			_httpMessage: [ServerResponse],
			[Symbol(asyncId)]: 1450,
			[Symbol(lastWriteQueueSize)]: 0,
			[Symbol(bytesRead)]: 0,
			[Symbol(asyncId)]: 1452,
			[Symbol(triggerAsyncId)]: 1450
		},
		httpVersionMajor: 1,
		httpVersionMinor: 1,
		httpVersion: '1.1',
		complete: true,
		headers: {
			Host: '10.10.10.10:81',
			'DingTalk-Flag': '1',
			'Proxy-Connection': 'keep-alive',
			'Upgrade-Insecure-Requests': '1',
			Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77 AliApp(DingTalk/4.5.11) com.laiwang.DingTalk/10450412 Channel/201200 language/zh-Hans-CN',
			'Accept-Language': 'zh-cn',
			'Accept-Encoding': 'gzip, deflate',
			Connection: 'keep-alive'
		},
		rawHeaders: ['Host',
			'10.10.10.10:81',
			'DingTalk-Flag',
			'1',
			'Proxy-Connection',
			'keep-alive',
			'Upgrade-Insecure-Requests',
			'1',
			'Accept',
			'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
			'User-Agent',
			'Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15G77 AliApp(DingTalk/4.5.11) com.laiwang.DingTalk/10450412 Channel/201200 language/zh-Hans-CN',
			'Accept-Language',
			'zh-cn',
			'Accept-Encoding',
			'gzip, deflate',
			'Connection',
			'keep-alive'
		],
		trailers: {},
		rawTrailers: [],
		upgrade: false,
		url: 'http://10.10.10.10:81/api/shop/front/trcOrder/submitOrder',
		method: 'GET',
		statusCode: null,
		statusMessage: null,
		client: Socket {
			connecting: false,
			_hadError: false,
			_handle: [TCP],
			_parent: null,
			_host: null,
			_readableState: [ReadableState],
			readable: true,
			_events: [Object],
			_eventsCount: 9,
			_maxListeners: undefined,
			_writableState: [WritableState],
			writable: true,
			allowHalfOpen: true,
			_bytesDispatched: 0,
			_sockname: null,
			_pendingData: null,
			_pendingEncoding: '',
			server: [Server],
			_server: [Server],
			_idleTimeout: 120000,
			_idleNext: [TimersList],
			_idlePrev: [TimersList],
			_idleStart: 274054,
			_destroyed: false,
			parser: [HTTPParser],
			on: [Function: socketOnWrap],
			_paused: false,
			_httpMessage: [ServerResponse],
			[Symbol(asyncId)]: 1450,
			[Symbol(lastWriteQueueSize)]: 0,
			[Symbol(bytesRead)]: 0,
			[Symbol(asyncId)]: 1452,
			[Symbol(triggerAsyncId)]: 1450
		},
		_consuming: true,
		_dumped: false,
		read: [Function]
	}
}

 

你可能感兴趣的:(AnyProxy)