二次封裝weex之stream模塊

Weex網絡請求

Weex網絡請求,使用其內置模塊Stream.express

Stream API

fetch(options, callback[,progressCallback])
發起網絡請求json

注意點:weex

1.body參數僅支持 string 類型的參數,請勿直接傳遞 JSON,必須先將其轉爲字符串。
2.body參數不支持Get請求,若是使用Get請求,須要在url上傳參。網絡

封裝一個本身的Stream模塊

封裝成request.js代碼:app

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

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

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
    });
  });
});

}
});ui

module.exports = request;this

使用封裝後的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);
});url

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'");});

相關文章
相關標籤/搜索