node· 发起网络Post和Get请求

node· 发起网络Post和Get请求

1】项目下终端载入 npm i axios
2】引入模块 const axios = require('axios');
3】使用(发起POST请求)

var data = { //请求参数
user:"abc"
        text: "1234567"
};

const headers = { //请求头
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post('http:/xxx/', data, headers)
.then(function(res) {
// console.log("结果 response:",res.data);
})
.catch(function(error) {
console.log("错误 error:", error);
});

4】使用(发起GET请求)

axios.get('http:xxx?xx=xx').then(
response => {
//response.data  返回拿回来的数据
console.log('请求成功了', response.data);
},
error => {
//error.message  返回错误的原因
console.log('请求失败了', error.message);
}
)
  

5】异步方法

//独立一个 Promise 方法函
let axiosPromise = function(data, headers) { //sql语句,values占位符
	return new Promise((resolve, reject) => { //reject(err);错误 resolve(rows)正确结果
		// 自定义方法含 
		axios.post('http://api.feieyun.cn/Api/Open/', data, headers)
			.then(function(res) {
				console.log("结果 response:", res.data);
				resolve(res.data); //不能返回单独整形,换成字符串就不报错
			})
			.catch(function(error) {
				console.log("错误 error:", error);
				reject('0'); //不能返回单独整形,换成字符串就不报错
			});
	})
}
/
342 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注