6

最开始 代码是

//network.js

function POST(url,params) {
    wx.request({
        url: url,
        data: params,
        method: 'GET',
        success: function (res) {
            console.log('返回结果:')
            console.log(res.data)
            return res.data
        }
    })
}

//login.js
const network = require('../../../utils/network.js');
...
//登录
login: function (login_res) {
    login_res = login_res.detail.value
    
    var url = app.globalData.baseUrl + 'api/login'
    var params = {
        username: login_res.username,
        password: login_res.password
    }
    
    var user_data = network.POST(url,params)
    console.log(user_data)
}

发现这取不到值,因为小程序的请求是异步的。
查资料说需要用到promise

ojbk

查资料+摸索
最终代码如下:

//network.js

const app = getApp()

function POST(url, params) {
    let promise = new Promise(function (resolve, reject) {
        wx.request({
            url: url,
            data: params,
            method: 'POST',
            success: function (res) {
                console.log('返回结果:')
                console.log(res.data)
                app.netWorkData.result = res.data
                resolve();
            }
        })
    });
    return promise
}
module.exports = {
    POST: POST
}

//app.js
App({
    netWorkData:{
        result: { code: -1, msg: '发起请求失败' }
    }
})

//登录
    login: function (login_res) {
        login_res = login_res.detail.value

        var url = app.globalData.baseUrl + 'api/login'
        var params = {
            username: login_res.username,
            password: login_res.password
        }

        network.POST(url,params).then(() => {
            //请求成功的操作
            var user_data = app.netWorkData.result
            
        });
    },

成功
oooojbk


南路
136 声望3 粉丝

吾尝终日而思矣,不如须臾之所学也