# 对接前端 开放平台一般对接服务端应用,开发者使用SDK来调用接口。 理论上来说,只要是客户端程序,都可以调用网关接口。因此,同样可以对接前端应用(H5、小程序、App)。 针对H5页面,配置方式如下: - 网关关闭签名校验。`ApiConfig.getInstance().setIgnoreValidate(true);` 由于是网页调用接口,把秘钥放在前端意义不大,干脆直接关闭签名校验。 - 设置统一的数据节点 ```java @Configuration public class ZuulConfig extends AlipayZuulConfiguration { static { ... ApiConfig.getInstance().setIgnoreValidate(true); ApiConfig.getInstance().setDataNameBuilder(new CustomDataNameBuilder()); ... } } ``` 设置后,网关统一的返回结果如下: ```json { "result": { ... }, "sign": "xxxxx" } ``` - 封装请求工具【可选】 封装请求,方便调用,针对vue的封装如下: ```js import axios from 'axios' // 创建axios实例 const client = axios.create({ baseURL: process.env.BASE_API, // api 的 base_url timeout: 5000, // 请求超时时间 headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) const RequestUtil = { /** * 请求接口 * @param method 接口名,如:goods.get,goods.get * @param version 版本号,如:1.0 * @param data 请求数据,json格式 * @param callback 成功回调 * @param errorCallback 失败回调 */ post: function(method, version, data, callback, errorCallback) { client.post(''/* 这里不用填 */, { method: method, version: version, biz_content: JSON.stringify(data) }).then(function(response) { const resp = response.result const code = resp.code // 成功,网关正常且业务正常 if (code === '10000' && !resp.sub_code) { callback(resp) } else { // 报错 Message({ message: resp.msg, type: 'error', duration: 5 * 1000 }) } }) .catch(function(error) { console.log('err' + error) // for debug errorCallback && errorCallback(error) }) } } export default RequestUtil ``` jQuery版本如下: ```js var RequestUtil = { /** * 请求接口 * @param method 接口名,如:goods.get,goods.get * @param version 版本号,如:1.0 * @param data 请求数据,json格式 * @param callback 成功回调 * @param errorCallback 失败回调 */ post: function(method, version, data, callback, errorCallback) { $.ajax({ url: 'http://localhost:8081/api' // 网关url , type: 'post' , headers: { 'Content-Type': 'application/x-www-form-urlencoded' } , data: { method: method, version: version, biz_content: JSON.stringify(data) } ,success:function(response){ var resp = response.result var code = resp.code // 成功,网关正常且业务正常 if (code === '10000' && !resp.sub_code) { callback(resp) } else { // 报错 alert(resp.msg); } } , error: function(error) { errorCallback && errorCallback(error) } }); } } ``` jQuery调用示例: ```js $(function () { var data = { id: 1 ,name: '葫芦娃' } RequestUtil.post('alipay.story.get', '1.0', data, function (result) { console.log(result) }); }) ``` 1.7.1开始支持接口名版本号放在url后面,规则:`http://host:port/{method}/{version}/`(最后的`/`不能少),如:`http://localhost:8081/story.demo.get/1.0/` 等同于:`http://localhost:8081/api?method=story.demo.get&version=1.0`。 把接口名版本号放在url后面的好处是调用接口一目了然,在浏览器F12调试的时候特别有用,可以一眼看到调用了哪些接口,否则将会看到全部都是api请求,需要点开查看request header才能知道到底调用了哪个接口