小东子的个人技术专栏

重点关注Android、Java、智能硬件、JavaEE、react-native,Swift,微信小程序


  • 首页

  • 归档

  • 标签
小东子的个人技术专栏

ES6中箭头函数的使用

发表于 2017-01-14   |   字数统计: 2,981(字)   |   阅读时长: 12(分)

基本用法

ES6允许使用“箭头”(=>)定义函数。

var f = v => v;

上面的箭头函数等同于:

var f = function(v) {
return v;
};

如果箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分。

var f = () => 5;
// 等同于
var f = function () { return 5 };

var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2) {
return num1 + num2;
};

如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return语句返回。

var sum = (num1, num2) => { return num1 + num2; }

由于大括号被解释为代码块,所以如果箭头函数直接返回一个对象,必须在对象外面加上括号。

var getTempItem = id => ({ id: id, name: “Temp” });

箭头函数可以与变量解构结合使用。

const full = ({ first, last }) => first + ‘ ‘ + last;

// 等同于
function full(person) {
return person.first + ‘ ‘ + person.last;
}

箭头函数使得表达更加简洁。

const isEven = n => n % 2 == 0;
const square = n => n * n;

上面代码只用了两行,就定义了两个简单的工具函数。如果不用箭头函数,可能就要占用多行,而且还不如现在这样写醒目。

箭头函数的一个用处是简化回调函数。

// 正常函数写法
[1,2,3].map(function (x) {
return x * x;
});

// 箭头函数写法
[1,2,3].map(x => x * x);

另一个例子是

// 正常函数写法
var result = values.sort(function (a, b) {
return a - b;
});

// 箭头函数写法

var result = values.sort((a, b) => a - b);

下面是rest参数与箭头函数结合的例子。

const numbers = (…nums) => nums;

numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]

const headAndTail = (head, …tail) => [head, tail];

headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]

使用注意点

箭头函数有几个使用注意点。

  • (1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

  • (2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

  • (3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替。

  • (4)不可以使用yield命令,因此箭头函数不能用作Generator函数。

上面四点中,第一点尤其值得注意。this对象的指向是可变的,但是在箭头函数中,它是固定的。

function foo() {
setTimeout(() => {
console.log(‘id:’, this.id);
}, 100);
}

var id = 21;

foo.call({ id: 42 });
// id: 42

上面代码中,setTimeout的参数是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它的真正执行要等到100毫秒后。如果是普通函数,执行时this应该指向全局对象window,这时应该输出21。但是,箭头函数导致this总是指向函数定义生效时所在的对象(本例是{id: 42}),所以输出的是42。

箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。下面是另一个例子。

function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
setInterval(() => this.s1++, 1000);
// 普通函数
setInterval(function () {
this.s2++;
}, 1000);
}

var timer = new Timer();

setTimeout(() => console.log(‘s1: ‘, timer.s1), 3100);
setTimeout(() => console.log(‘s2: ‘, timer.s2), 3100);
// s1: 3
// s2: 0

上面代码中,Timer函数内部设置了两个定时器,分别使用了箭头函数和普通函数。前者的this绑定定义时所在的作用域(即Timer函数),后者的this指向运行时所在的作用域(即全局对象)。所以,3100毫秒之后,timer.s1被更新了3次,而timer.s2一次都没更新。

箭头函数可以让this指向固定化,这种特性很有利于封装回调函数。下面是一个例子,DOM事件的回调函数封装在一个对象里面。

var handler = {
id: ‘123456’,

init: function() {
document.addEventListener(‘click’,
event => this.doSomething(event.type), false);
},

doSomething: function(type) {
console.log(‘Handling ‘ + type + ‘ for ‘ + this.id);
}
};

上面代码的init方法中,使用了箭头函数,这导致这个箭头函数里面的this,总是指向handler对象。否则,回调函数运行时,this.doSomething这一行会报错,因为此时this指向document对象。

this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。

所以,箭头函数转成ES5的代码如下。

// ES6
function foo() {
setTimeout(() => {
console.log(‘id:’, this.id);
}, 100);
}

// ES5
function foo() {
var _this = this;

setTimeout(function () {
console.log(‘id:’, _this.id);
}, 100);
}

上面代码中,转换后的ES5版本清楚地说明了,箭头函数里面根本没有自己的this,而是引用外层的this。

请问下面的代码之中有几个this?

function foo() {
return () => {
return () => {
return () => {
console.log(‘id:’, this.id);
};
};
};
}

var f = foo.call({id: 1});

var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1

上面代码之中,只有一个this,就是函数foo的this,所以t1、t2、t3都输出同样的结果。因为所有的内层函数都是箭头函数,都没有自己的this,它们的this其实都是最外层foo函数的this。

除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target。

function foo() {
setTimeout(() => {
console.log(‘args:’, arguments);
}, 100);
}

foo(2, 4, 6, 8)
// args: [2, 4, 6, 8]

上面代码中,箭头函数内部的变量arguments,其实是函数foo的arguments变量。

另外,由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。

(function() {
return [
(() => this.x).bind({ x: ‘inner’ })()
];
}).call({ x: ‘outer’ });
// [‘outer’]

上面代码中,箭头函数没有自己的this,所以bind方法无效,内部的this指向外部的this。

长期以来,JavaScript语言的this对象一直是一个令人头痛的问题,在对象方法中使用this,必须非常小心。箭头函数”绑定”this,很大程度上解决了这个困扰。
嵌套的箭头函数

箭头函数内部,还可以再使用箭头函数。

下面是一个ES5语法的多重嵌套函数。

function insert(value) {
return {into: function (array) {
return {after: function (afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}};
}};
}

insert(2).into([1, 3]).after(1); //[1, 2, 3]

上面这个函数,可以使用箭头函数改写。

let insert = (value) => ({into: (array) => ({after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array;
}})});

insert(2).into([1, 3]).after(1); //[1, 2, 3]

下面是一个部署管道机制(pipeline)的例子,即前一个函数的输出是后一个函数的输入。

const pipeline = (…funcs) =>
val => funcs.reduce((a, b) => b(a), val);

const plus1 = a => a + 1;
const mult2 = a => a * 2;
const addThenMult = pipeline(plus1, mult2);

addThenMult(5)
// 12

如果觉得上面的写法可读性比较差,也可以采用下面的写法。

const plus1 = a => a + 1;
const mult2 = a => a * 2;

mult2(plus1(5))
// 12

箭头函数还有一个功能,就是可以很方便地改写λ演算。

// λ演算的写法
fix = λf.(λx.f(λv.x(x)(v)))(λx.f(λv.x(x)(v)))

// ES6的写法
var fix = f => (x => f(v => x(x)(v)))
(x => f(v => x(x)(v)));

上面两种写法,几乎是一一对应的。由于λ演算对于计算机科学非常重要,这使得我们可以用ES6作为替代工具,探索计算机科学。
函数绑定

箭头函数可以绑定this对象,大大减少了显式绑定this对象的写法(call、apply、bind)。但是,箭头函数并不适用于所有场合,所以ES7提出了“函数绑定”(function bind)运算符,用来取代call、apply、bind调用。虽然该语法还是ES7的一个提案,但是Babel转码器已经支持。

函数绑定运算符是并排的两个双冒号(::),双冒号左边是一个对象,右边是一个函数。该运算符会自动将左边的对象,作为上下文环境(即this对象),绑定到右边的函数上面。

foo::bar;
// 等同于
bar.bind(foo);

foo::bar(…arguments);
// 等同于
bar.apply(foo, arguments);

const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return obj::hasOwnProperty(key);
}

如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。

var method = obj::obj.foo;
// 等同于
var method = ::obj.foo;

let log = ::console.log;
// 等同于
var log = console.log.bind(console);

由于双冒号运算符返回的还是原对象,因此可以采用链式写法。

// 例一
import { map, takeWhile, forEach } from “iterlib”;

getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));

// 例二
let { find, html } = jake;

document.querySelectorAll(“div.myClass”)
::find(“p”)
::html(“hahaha”);

尾调用优化

什么是尾调用?

尾调用(Tail Call)是函数式编程的一个重要概念,本身非常简单,一句话就能说清楚,就是指某个函数的最后一步是调用另一个函数。

function f(x){
return g(x);
}

上面代码中,函数f的最后一步是调用函数g,这就叫尾调用。

以下三种情况,都不属于尾调用。

// 情况一
function f(x){
let y = g(x);
return y;
}

// 情况二
function f(x){
return g(x) + 1;
}

// 情况三
function f(x){
g(x);
}

上面代码中,情况一是调用函数g之后,还有赋值操作,所以不属于尾调用,即使语义完全一样。情况二也属于调用后还有操作,即使写在一行内。情况三等同于下面的代码。

function f(x){
g(x);
return undefined;
}

尾调用不一定出现在函数尾部,只要是最后一步操作即可。

function f(x) {
if (x > 0) {
return m(x)
}
return n(x);
}

上面代码中,函数m和n都属于尾调用,因为它们都是函数f的最后一步操作。
尾调用优化

尾调用之所以与其他调用不同,就在于它的特殊的调用位置。

我们知道,函数调用会在内存形成一个“调用记录”,又称“调用帧”(call frame),保存调用位置和内部变量等信息。如果在函数A的内部调用函数B,那么在A的调用帧上方,还会形成一个B的调用帧。等到B运行结束,将结果返回到A,B的调用帧才会消失。如果函数B内部还调用函数C,那就还有一个C的调用帧,以此类推。所有的调用帧,就形成一个“调用栈”(call stack)。

尾调用由于是函数的最后一步操作,所以不需要保留外层函数的调用帧,因为调用位置、内部变量等信息都不会再用到了,只要直接用内层函数的调用帧,取代外层函数的调用帧就可以了。

function f() {
let m = 1;
let n = 2;
return g(m + n);
}
f();

// 等同于
function f() {
return g(3);
}
f();

// 等同于
g(3);

上面代码中,如果函数g不是尾调用,函数f就需要保存内部变量m和n的值、g的调用位置等信息。但由于调用g之后,函数f就结束了,所以执行到最后一步,完全可以删除 f(x) 的调用帧,只保留 g(3) 的调用帧。

这就叫做“尾调用优化”(Tail call optimization),即只保留内层函数的调用帧。如果所有函数都是尾调用,那么完全可以做到每次执行时,调用帧只有一项,这将大大节省内存。这就是“尾调用优化”的意义。

注意,只有不再用到外层函数的内部变量,内层函数的调用帧才会取代外层函数的调用帧,否则就无法进行“尾调用优化”。

function addOne(a){
var one = 1;
function inner(b){
return b + one;
}
return inner(a);
}

上面的函数不会进行尾调用优化,因为内层函数inner用到了外层函数addOne的内部变量one。

小东子的个人技术专栏

Android应用开发中三种常见的图片压缩方法

发表于 2017-01-14   |   字数统计: 835(字)   |   阅读时长: 4(分)

Android应用开发中三种常见的图片压缩方法,分别是:质量压缩法、比例压缩法(根据路径获取图片并压缩)和比例压缩法(根据Bitmap图片压缩)。

1、质量压缩法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}

2、图片按比例大小压缩方法(根据路径获取图片并压缩)

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
private Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}

3、图片按比例大小压缩方法(根据Bitmap图片压缩)

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
private Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
小东子的个人技术专栏

React-Native中navigator.pop()后如何更新前一个页面

发表于 2017-01-14   |   字数统计: 574(字)   |   阅读时长: 3(分)

1、问题提出

React-Native中navigator.pop()后如何更新前一个页面,这是一个最为常见得问题。

2、问题的描述

比如说,我们开发应用的时候,上传头像是一个最为常见的功能,我点击选择打开图库的按钮之后,push到图库的页面,我们在上传成功后,需要pop回到当前页面,并把图片路径传到当前页面。

3、React-Native中的解决办法

这个问题对于一个有Android和ios开发经验的程序员首先想到的就是回调函数或者广播机制等。其实在React-Native中同样也可用回调函数来解决这个问题。本来想以android来举例实现,最后还是算了直接上React-Native吧。

  1. 在A页面中实现一个声明一个函数refresView()
  2. 在A页面push参数中增加一个回掉函数callBack(msg)
  3. 在B页面pop时候调用callBack将值传回,更新界面

4.代码的实现

4.A页面的实现

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Navigator,
ToastAndroid,
View
} from 'react-native';
import Button from './Button';
import Test from './test';
var _navigator;
var d;
class Hello2 extends Component {
constructor(props){
super(props);
d = this;
this.state = {city:''}
// this.refeshView = this.refeshView.bind(this);
}
configureScene(route){
return Navigator.SceneConfigs.FadeAndroid;
}
refeshView(msg){
console.log('刷新');
d.setState({'city':msg});
console.log('end');
}
renderScene(router, navigator){
console.log(d);
_navigator = navigator;
if(router.id === 'main'){
return <View style={styles.container}>
<Button onPress={() => {
console.log('start');
_navigator.push({title:'MainPage',id:'page',callBack:(msg)=>{
console.log(d);
d.refeshView(msg);
console.log('end');}});
}} text={'打开'} style={styles.instructions} disabled = {false}/>
<Text style={styles.welcome}>
{d.state.city}
</Text>
<Text style={styles.instructions}>
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
}else if(router.id === 'page'){
return (
<Test navigator={navigator} router={router}/>
);
}
}
render() {
return (
<Navigator
initialRoute={{ title: 'Main', id:'main'}}
configureScene={this.configureScene}
renderScene={this.renderScene} />
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Hello2', () => Hello2);

4.2、B页面的实现

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
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
var _navigator;
import Button from './Button';
class Test extends Component {
render() {
return (
<View style={{flex:1}}>
<Button onPress={() => {
console.log(this.props);
this.props.router.callBack('I am a Student');
this.props.navigator.pop();
}} text={'返回'} style={styles.instructions} disabled = {false}/>
</View>
);
}
}
const styles = StyleSheet.create({
instructions: {
textAlign: 'center',
color: '#126798',
marginTop: 50,
}
});
module.exports = Test;

代码非常的简单,谢谢大家学习。

5、效果展示

这里写图片描述

这里写图片描述

这里写图片描述

小东子的个人技术专栏

node.js 操作MongoDB数据库

发表于 2017-01-14   |   字数统计: 271(字)   |   阅读时长: 1(分)

1.初始化数据

启动MongoDB服务,在test数据库中插入一条实例数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> use part_0;
switched to db part_0
> db.user.insert({"username":"lidong"});
WriteResult({ "nInserted" : 1 })
> db.user.insert({"username":"lizirui","sex":"1"});
WriteResult({ "nInserted" : 1 })
> db.user.find();
{ "_id" : ObjectId("57f4898418cde5e4b9fe7a92"), "username" : "lidong" }
{ "_id" : ObjectId("57f4899918cde5e4b9fe7a93"), "username" : "lizirui", "sex" : "1" }
> db.user.insert({"username":"liziqi","sex":"1"});
WriteResult({ "nInserted" : 1 })
> db.user.insert({"username":"lizihan","sex":"1"});
WriteResult({ "nInserted" : 1 })
> db.user.find();
{ "_id" : ObjectId("57f4898418cde5e4b9fe7a92"), "username" : "lidong" }
{ "_id" : ObjectId("57f4899918cde5e4b9fe7a93"), "username" : "lizirui", "sex" : "1" }

2.在Node.js中引入MongoDB模块

1
npm install mongodb

3.编写test.js测试连接

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
var mongo = require('mongodb');
var host = "localhost";
var port = 27017;
//创建MongoDB数据库所在服务器的Server对象
var server = new mongo.Server(host, port, {auto_reconnect:true});
//创建MongoDB数据库
var db = new mongo.Db('part_0', server, {saft:true});
//数据库连接操作
db.open(function(err, db){
if(err) {
console.log('连接数据库发生错误');
throw err;
}
else{
console.log("成功建立数据库连接");
db.collection('user',{safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
console.log('-----------');
collection.find(function(error,cursor){
cursor.each(function(error,doc){
if(doc){
console.log("name:"+doc.username+" sex:"+doc.sex);
}
});
});
}
});
db.close();
}
});
db.on('close',function(err,db){
if (err) {throw err;}
else{
console.log("成功关闭数据库");
}
});

4.运行结果

这里写图片描述

小东子的个人技术专栏

Node.js http服务器搭建和发送http的get,post请求

发表于 2017-01-14   |   字数统计: 336(字)   |   阅读时长: 2(分)

1.Node.js 搭建http服务器

1.1创建server.js

1
2
3
4
5
6
7
8
var http = require('http');
var querystring = require('querystring');
http.createServer(function (request, response) {
console.log('receive request');
response.writeHead(200, { 'Content-Type': 'text-plain' });
response.end('Hello World\n');
}).listen(8124);
console.log("node server start ok port "+8124);

1.2执行 server.js

1
node server.js

1.3服务器启动

如图:
这里写图片描述

通过浏览器地址请求:http://localhost:8124

这里写图片描述

2.发送GET请求

2.1发送get请求通过聚合服务器获取微信新闻数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http = require('http');
var querystring = require('querystring');
http.get('http://v.juhe.cn/weixin/query?key=f16af393a63364b729fd81ed9fdd4b7d&pno=1&ps=10', function (response) {
var body = [];
console.log(response.statusCode);
console.log(response.headers);
console.log(response);
response.on('data', function (chunk) {
body.push(chunk);
});
response.on('end', function () {
body = Buffer.concat(body);
console.log(body.toString());
});
});

2.2 执行 get_demo.js

1
node get_demo.js

2.3获取的结果打印

这里写图片描述

3.发送POST请求

3.1发送post请求通过聚合服务器获取微信闻数据

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
var http = require('http');
var querystring = require('querystring');
var postData = querystring.stringify({
'key' : 'f16af393a63364b729fd81ed9fdd4b7d',
'pno':'1',
'ps':10
});
var options = {
hostname: 'v.juhe.cn',
path: '/weixin/query',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();

3.2 执行 post_demo.js

1
node post_demo.js

3.3获取的结果打印

这里写图片描述

1…567…10
李东

李东

细节决定成败,点滴铸就辉煌

46 文章
18 标签
© 2017 李东
由 Hexo 强力驱动
主题 - NexT.Pisces