账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    uni-app中使用rpc协议请求
    • 2020-01-01 00:00
    • 11
    46
    0

    uni-app中使用rpc协议请求

    uni-apprpc

     阅读约 3 分钟

    1、首先安装一个rpc 包 npm install js-jsonrpc-request
    2、通用请求ajax.js简单封装。
    注意的是:入参我的是数组,出参是一个简单变量。github给的例子,入参是对象,出参也是对象,这块有需要可以修改。
    `import JsonRpcClient from 'js-jsonrpc-request';
    import requestUrl from '@/common/requestURL.js';

    const jsonrpc = new JsonRpcClient({

    apiRoute: requestUrl.basicURL,
    headers: {
        'X-API-CLIENT': 'key',
    },
    withMeta: false,

    });

    const ajax = (opt) => {

    opt = opt || {};
    opt.url = opt.url ;
    opt.data = opt.data || null;
    opt.prompt = opt.prompt || '加载中...';
    
    opt.success = opt.success || function() {};
    uni.showLoading({
        title: opt.prompt
    });
    jsonrpc
    .request(opt.url, opt.data)
     .then((res) => {
        console.log('data', res);
        uni.hideLoading();
        opt.success(res.data);
    })
    .catch((err) =>{
        var  str =  JSON.stringify(err);
        uni.showToast({
                title: str,
                duration: 522000,
                icon: 'none'
            });
    });
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 在uni-app中,使用rpc协议请求主要是通过在客户端和服务器之间建立TCP连接,然后使用TCP协议来传输数据。以下是一个简单的示例:

      首先,我们需要在服务器端编写一个RPC服务器,它会接收客户端的请求,然后发送相应的响应。

      ```javascript const { WebServer, WebClient } = require('uni-app');

      const webServer = new WebServer({ port: 8080, protocol: 'http', });

      webServer.on('request', (request, response) => { response.send('Hello, world!'); });

      webServer.listen(); ```

      然后,我们需要在客户端编写一个RPC客户端,它会发送请求到服务器,然后接收服务器的响应。

      ```javascript const { WebClient, WebServer } = require('uni-app');

      const client = new WebClient({ url: 'http://localhost:8080', });

      client.send({ method: 'GET', path: '/users', });

      client.on('response', (response) => { console.log(response.data); });

      client.listen(); ```

      以上就是一个基本的RPC请求过程。需要注意的是,由于RPC协议的复杂性,实际的实现可能会更复杂,需要考虑更多的细节,例如错误处理、网络问题、数据传输的格式等。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部