react native使用阿里云里的天气api
用react native开发天气APP

加密

使用crypto-js进行加密,包括HMACSHA256和BASE64

安装crytpo-js

1
npm install crypto-js --save

使用

1
2
3
let crypto = require("crypto-js");
let sign = crypto.HmacSHA256(stringToSign, secret); //先进行HMAC SHA256加密。官方文档并无nodejs相关的说明,参照其他语言进行摸索
sign = crypto.enc.Base64.stringify(sign); //将HMAC SHA256加密的原始二进制数据后进行Base64编码

生成随机字符串

使用node-uuid

安装

1
npm install node-uuid --save

使用

1
2
let uuid = require('node-uuid');
let nonce = uuid.v4();

react native fetch

1
2
3
4
5
6
7
fetch(Url, {
method: 'GET',
}).then(function(response) {
//response并不是单纯返回的JSON数据格式,使用使用response.json()处理
}).catch(function(err) {
console.log(JSON.stringify(err));
});

接口认证

完成代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
let crypto = require("crypto-js"); //使用scrypot-js进行HmacSHA256加密、BASE64加密。 npm install crypto-js --save
let uuid = require('node-uuid'); //生成随机字符串 npm install node-uuid --save

let getWeather = () => {
let Accept = 'application/json';
let ContentType = 'application/json';
let Timestamp = Date.now();
let Nonce = uuid.v4();
let key = 'XXXX'; //阿里云API网关的 应用AppKey
let secret = 'xxxx'; //阿里云API网关的 应用的秘钥
let Headers =
'X-Ca-Key' + ":" + key + "\n" +
'X-Ca-Nonce' + ":" + Nonce + "\n" +
'X-Ca-Request-Mode' + ":" + 'debug' + "\n" +
'X-Ca-Stage' + ":" + 'RELEASE' + "\n" +
'X-Ca-Timestamp' + ":" + Timestamp + "\n" +
'X-Ca-Version' + ":" + '1' + "\n";


let Url = 'http://weather.market.alicloudapi.com/area-to-weather?area=北京';
let stringToSign =
'GET' + "\n" +
Accept + "\n" +
'' + "\n" +
ContentType + "\n" +
'' + "\n" +
Headers +
'/area-to-weather?area=北京';//此处为访问域名后面的字符串


let sign = crypto.HmacSHA256(stringToSign, secret); //先进行HMAC SHA256加密。官方文档并无nodejs相关的说明,参照其他语言进行摸索
sign = crypto.enc.Base64.stringify(sign); //将HMAC SHA256加密的原始二进制数据后进行Base64编码

fetch(Url, {
method: 'GET',
headers: {
'Accept': Accept,
'Content-Type': ContentType,
'X-Ca-Request-Mode': 'debug',
'X-Ca-Version': 1,
'X-Ca-Signature-Headers': 'X-Ca-Request-Mode,X-Ca-Version,X-Ca-Stage,X-Ca-Key,X-Ca-Timestamp,X-Ca-Nonce',
'X-Ca-Stage': 'RELEASE',
'X-Ca-Key': key,
'X-Ca-Timestamp': Timestamp,
'X-Ca-Nonce': Nonce,
'X-Ca-Signature': sign
}
}).then(function(response) {//response并不是单纯返回的JSON数据格式,使用使用response.json()处理
if (response.status == 200)
response.json().then((data) => {
console.log(JSON.stringify(data))
})
}).catch(function(err) {
console.log(JSON.stringify(err));
});
}

本文地址: http://gehaiqing.com/2016/11/23/react-native-aliyun-weather-api/