通过 Proxy 汉化 restful 接口

时间:2022-05-03
本文章向大家介绍通过 Proxy 汉化 restful 接口,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文节选自《Netkiller Web 手札》

1.4.14.6. 通过 Proxy 汉化 restful 接口

通过 proxy 汉化 restful 接口返回的 json 字符串。

背景,有这样一个需求,前端HTML5通过ajax与restful交互,ajax会显示接口返回json数据,由于js做了混淆无法修改与restful交互的逻辑,但是json反馈结果需要汉化。

汉化前接口如下,返回message为 "message":"Full authentication is required to access this resource"

			neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json

{"timestamp":1505206067543,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/restful/member/get/1.json"}   

建立一个代理服务器,代理介于用户和接口之间,ajax 访问接口需要经过这个代理服务器中转。

增加 /etc/nginx/conf.d/api.netkiller.cn.conf 配置文件

			server {
	listen 80;
	server_name api.netkiller.cn;

	charset utf-8;
	
	location / {
		proxy_pass http://localhost:8443;
		proxy_http_version 1.1;
		proxy_set_header    Host    $host;

		sub_filter_types application/json; 
        sub_filter 'Full authentication is required to access this resource'  '用户验证错误';
        sub_filter_once off;
	}

}			

所谓汉化就是字符串替换,使用nginx sub_filter 模块。

重新启动 nginx 然后测试汉化效果

			neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json

{"timestamp":1505208931927,"status":401,"error":"Unauthorized","message":"用户验证错误","path":"/restful/member/get/1.json"}