二次封装weex之stream模块

DaLei 2019-06-28

Weex网络请求

Weex网络请求,使用其内置模块Stream.

Stream API

fetch(options, callback[,progressCallback])
发起网络请求

注意点:

1.body参数仅支持 string 类型的参数,请勿直接传递 JSON,必须先将其转为字符串。
2.body参数不支持Get请求,如果使用Get请求,需要在url上传参。

封装一个自己的Stream模块

封装成request.js代码:

const stream = weex.requireModule("stream");
const modal = weex.requireModule("modal");
const requestMethod = ["post", "get"];
const request = {};

requestMethod.forEach(method => {
request[method] = (url = "", params = "", config = {}) => {

let requestUrl = url;
let headers = Object.assign(
  {}, { "Content-Type": "application/x-www-form-urlencoded" }, config.headers
);

if (method === "get") {
  requestUrl = `${url}?${params}`;
  params = "";
}
return new Promise((resolve, reject) => {
  stream.fetch({
    method,
    url: requestUrl,
    type: "json",
    headers,
    body: params,
    timeout: 8000,
  }, function (res) {
    if (res.ok) {
      let data = res.data;
      if (data && data.control.error == 0) {
        resolve(data.data);

      } else {
        modal.confirm({
          message: data.control.msg,
          duration: 0.3
        });
        
      }
      return;
    }
    reject({
      status: res.status,
      msg: res.statusText
    });
    modal.confirm({
      message: res.statusText,
      duration: 0.3
    });
  });
});

}
});

module.exports = request;

使用封装后的stream模块

let request = require("./request.js");
request.post(
'http://localhost:9090/wap/open/indexHome',
userName=${this.userName}&age=${this.age}
).then((res)=>{
this.userName = res.userName;
this.age = res.age;
},(e)=>{
console.log(e);
});

Express接收请求

let express = require('express');
let bodyParser = require('body-parser');
let app = module.exports = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.post('/wap/open/indexHome',function(req,res){

let {userName,age} = req.body;
res.json({

control:{
  error: 0
},
data: {
   userName,
   age
}

});

});

app.listen(9090,function(){
console.log("Server listening on port :'9090'");
});

相关推荐