Files
SOP/doc/docs/files/10100_传统web开发.md
2019-07-24 16:30:08 +08:00

150 lines
3.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 传统web开发
本篇介绍如何使用SOP进行传统web服务开发即对接前端应用H5、小程序、App
- 网关ZuulConfig继承WebappZuulConfiguration类
```java
@Configuration
public class ZuulConfig extends WebappZuulConfiguration {
static {
new ManagerInitializer();
}
}
```
设置完毕,网关不在进行签名验证,网关统一的返回结果如下:
```json
{
"result": {
...
}
}
```
- 微服务OpenServiceConfig继承WebappServiceConfiguration类
```java
public class OpenServiceConfig extends WebappServiceConfiguration {
...
}
```
其它内容不变
- 封装请求工具【可选】
封装请求方便调用针对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才能知道到底调用了哪个接口