Table of Contents
Vesrion:Asp.Net Core 3.1
微信小程序 wx.request 封装
条件:
小程序后台要加入https://api.**.com,域名要备案、域名要启用https协议。
微信小程序,通用Http请求方式,及后台接收参数的方式(后台为 .net core)
小程序客户端 http get 原型
office doc:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
method: 'GET',
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
},
fail: function(res) {
console.log("失败");
}
})
result:
console.log("app.js获取的员工信息为:jsonstr==" + JSON.stringify(res))
request ok output:
app.js获取的员工信息为:jsonstr=={
"data":[{"_openid":null,"UserName":null,"Password":null,"UserName_zh_CN":"888","Email":null,"Mobile":"777","UserInfo":{"nickName":null,"gender":0,"language":null,"city":null,"province":null,"country":null,"avatarUrl":null},"IsEmployeeAuthorized":false,"EmployeeStatus":0,"IsAdmin":false,"IsAuthorized":false,"IsDeleted":false,"LastloginIP":null,"CreatedOnUtc":"2020-09-08T15:09:58.674Z","UpdatedOnUtc":"2020-09-08T15:13:42.024Z","LastloginOnUtc":"0001-01-01T00:00:00Z","EmployeeRoles":{"Appid":null,"AuthorOpenid":null,"AuthorUnionid":null,"OriginalId":null,"Name":null,"SystemName":null,"Level":0,"Mark":null,"DisplayOrder":0,"Active":false,"IsDeleted":false,"CreatedOnUtc":"0001-01-01T00:00:00Z","UpdatedOnUtc":"0001-01-01T00:00:00Z","_id":null},"Warehouses":[],"_id":"5f579ec6cc6dcf712085c0e7"}],
"header":{"Server":"nginx/1.14.0 (Ubuntu)","Date":"Wed, 09 Sep 2020 13:31:33 GMT","Content-Type":"application/json; charset=utf-8","Transfer-Encoding":"chunked","Connection":"keep-alive"},
"statusCode":200,
"cookies":[],
"errMsg":"request:ok
"}
request error output:
app.js获取的员工信息为:jsonstr=={
"data":"<html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>502 Bad Gateway</h1></center>\r\n<hr><center>nginx/1.14.0 (Ubuntu)</center>\r\n</body>\r\n</html>\r\n",
"header":{"Server":"nginx/1.14.0 (Ubuntu)","Date":"Wed, 09 Sep 2020 13:39:59 GMT","Content-Type":"text/html","Content-Length":"182","Connection":"keep-alive"},
"statusCode":502,
"cookies":[],
"errMsg":"request:ok"}
小程序客户端 http get 原型+token
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
method: 'GET',
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
'Token': 'xdddeer44' //Token 值
},
success (res) {
console.log(res.data)
},
fail: function(res) {
console.log("失败");
}
})
小程序客户端 http get 原型+Promise
return new Promise((resolve,reject)=>{
wx.showLoading({
title: '正在加载',
})
wx.request({
url: _url,
data: data,
method: method,
header: {
'content-type': 'application/x-www-form-urlencoded',
},
success(res) {
let {code}=res.data;
if(code===0) {
resolve(res.data);
wx.hideLoading()
}else {
wx.showToast({
title: '数据请求误',
}) }
},
fail(){
reject('接口请求有误,有检查');
}
});
});
},
小程序客户端 http post 原型
onLoad: function () {
var that = this;
wx.request({
url: 'https://www.51sdfbavvvy.cn/Mssm/HerNeeo.ashx',
data:{
'TypeID': '0',
'ImageID': 'ZNK',
'Name': ''
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success:function(res) {
that.setData({
array: res.data.array
})
},
fail:function(res){
console.log('submit fail');
},
complete:function(res){
console.log('submit complete');
}
})
wx.request的封装
var options = {
url: url,
method: "POST",
body: JSON.stringify(data),
encoding: null // 最坑的一句代码,没有得到的二进制image内容就是错乱的
//responseType: 'arraybuffer', 小程序端要这么写
};
console.log(options)
const apireq = options => new Promise((resolve, reject) => request(options, (err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
}));
// 得到 二维码数据流
let image = await apireq(options)
var cloudPath = "Outdoors/" + event.outdoorid + "/QrCode.jpg"
wx.request的Promise封装
配置域名
一般情况下,项目中的域名前缀都是配置在 app.js 中
App({
onLaunch: function() {
},
globalData: {
userInfo: null,
loginCode: null,
version: '1.0.0',
host: 'https://**',
}
})
封装 wx.request
在小程序目录下建立 api 文件夹,并在文件夹下创建 api.js 脚本。下面开始封装 wx.request
const app = getApp()
const request = (url, options) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${app.globalData.host}${url}`,
method: options.method,
data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
header: {
'Content-Type': 'application/json; charset=UTF-8',
'x-token': 'x-token' // 看自己是否需要
},
success(request) {
if (request.data.code === 2000) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) {
reject(error.data)
}
})
})
}
const get = (url, options = {}) => {
return request(url, { method: 'GET', data: options })
}
const post = (url, options) => {
return request(url, { method: 'POST', data: options })
}
const put = (url, options) => {
return request(url, { method: 'PUT', data: options })
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {
return request(url, { method: 'DELETE', data: options })
}
module.exports = {
get,
post,
put,
remove
}
管理 api 接口
项目中的 api 大部分都是可以复用的。为了后期方便维护管理,这个时候需要把 api 提出来。有多种方法,比如可以按模块建立相应的 js 脚本。如下:
const login = '/user/login' // 登录
module.exports = {
login
}
使用封装过后的 api
import api from '../api/api'
import { login } from '../**/conf' // 链接注意填写正确
api.post(login, {
data: ''
}).then(res => {
if(){}
}).catch(err => {
wx.showToast({
title: err.message,
icon: 'none'
})
})
post 请求就是api.post()...,get 请求就是api.get()...
1.
method:"GET"
contentType:"application/json"
[Query String Paramters]
core:
func(dynamic key) or Request.QueryString("key")
2.
method :"POST"
contentType:"application/x-www-form-urlencoded"
[Form Data]
core:
HttpContext.Request.Form["key"].ToString()
3.
method:"POST"
contentType:"application/json"
[Payload]
core"
func([FormBody] Dictionary <string string> object)
Node.js发送请求
- Node.js发送请求,需要用到request这个模块
- request官网
- 先导入这个模块
npm install request --save
GET请求
var url = 'http://192.168.0.102:3000/home?name=xmg'
// 发送Get请求
// 第一个参数:请求的完整URL,包括参数
// 第二个参数:请求结果回调函数,会传入3个参数,第一个错误,第二个响应对象,第三个请求数据
request(url,function (error, response, data) {
console.log(data)
});
Post请求
- post请求有3种方式,由请求头中的content-type决定,属于哪一种post请求
- application/x-www-form-urlencoded: 普通http请求方式,参数是普通的url参数拼接
- application/json: JSON请求方式,参数是json格式
- multipart/form-data: 文件上传
application/x-www-form-urlencoded
var url = 'http://192.168.0.102:3000/home?name=xmg'
request.post({url:url, form:{key:'value'}}, function(error, response, body) {
if (!error && response.statusCode == 200) {
}
})
application/json
var url = 'http://192.168.0.102:3000/home'
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
}
});
multipart/form-data
var url = 'http://192.168.0.102:3000/home'
var formData = {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: new Buffer([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:url, formData: formData}, function (error, response, body) {
if (!error && response.statusCode == 200) {
}
})
服务器Web API端(.Net core 3.x)
create service
step 1:create service
public partial interface IProductStockTypeService
{
/// <summary>
/// mongodb数据库中的产品库存型号
/// </summary>
/// <returns></returns>
Task<List<ProductStockType>> GetAllProductStockType();
}
step 2:register service
Api Controllers
/// <summary>
/// https://api.usdotnet.com/api/NewEmployee/NewEmployee
/// </summary>
/// <returns></returns>
[HttpGet("[action]")]
public async Task<IActionResult> NewEmployee()
{
var result = new Employee();
return Ok(result);
}
result:
{"Appid":null,"AuthorOpenid":null,"AuthorUnionid":null,"OriginalId":null,"_openid":null,"UserName":null,"Password":null,"UserName_zh_CN":null,"Email":null,"Mobile":null,"UserInfo":{"nickName":null,"gender":0,"language":null,"city":null,"province":null,"country":null,"avatarUrl":null},"IsEmployee":false,"EmployeeStatus":0,"IsAdmin":false,"IsAuthorized":false,"IsDeleted":false,"CreatedOnUtc":"0001-01-01T00:00:00","UpdatedOnUtc":"0001-01-01T00:00:00","LastloginOnUtc":"0001-01-01T00:00:00","EmployeeRoles":[],"Warehouses":[],"Id":null}
step 3:http://localhost:5000/api/productstocktype
public partial class ProductStockType : BaseEntity
{
public string Name { set; get; }
}
[{"name":"QJ12B-Y","id":"5f43a46054a35fe1d20785d0"},{"name":"FS1","id":"5f43a46054a35fe1d2078633"}]
这里出现了两个问题:
(1)使用Asp.Net Core 3.1 的Web Api 返回数据发现字段名称被转换为小驼峰格式。首字母都被改成小写了。
(2)小程序端需要的时 _id,但这里输出的为id
考虑到web api服务于多终端,如网页版,就不在这里解决。留在小程序端来解决。
step 4:设置json字符串大小写原样输出
//json字符串大小写原样输出
//services.AddControllers();
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
}
);
output:
[{"Name":"QJ12B-Y","id":"5f43a46054a35fe1d20785d0"},{"Name":"FS1","id":"5f43a46054a35fe1d2078633"}]
调用方式:
//准备请求数据
var url = string.Format(" https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}",
accessToken, nextOpenId);
小程序客户端
// ----发送选择的股票和日期 ---
sendStockCode: function(e) {
var that = this;
var stockCode = this.data.inputValue;
//请求网络数据
wx.request({
url: "https://api.usdotnet.com/api/values",
success: function(res) { //请求成功
console.log(res); //在调试器里打印网络请求到的json数据
},
fail: function(res) { // 请求失败
}
});
wx.request({
url: 'https://api.usdotnet.com/api/stockinfo', //本地服务器地址
data: {
stockCode: this.data.inputValue,
date: 'abc',
},
method: 'GET',
header: {
'content-type': 'application/json' //默认值
},
success: function(res) {
console.log(" wx.request({url: 'https://api.usdotnet.com/api/stockinfo:" + res);
that.setData({
stockInfo: res.data
})
//传入给画布要用到的参数
preStockClose = res.data.stock_yesterday_m_fClose; //股票昨日收盘价
pre_shanghaiCompositeIndexClose = res.data.shanghaiCompositeIndex_yesterday_m_fClose; //上海指数昨日收盘价
firsttime = res.data.firsttime;
},
fail: function(res) {
console.log("失败");
}
})
//点击发送,调用服务器上的 sendMessage 方法
this.hubConnect.send("SendMessage", stockCode, "20190401");
// 点击发送,调用服务器上的 sendMessage 方法
// this.hubConnect.send("SendMessagedp", "SZ002930", "20190401");
},
伍华聪微信小程序的Web API接口设计及常见接口实现
https://www.cnblogs.com/wuhuacong/p/7488939.html