【问题标题】:How to use Restler Rest client library instead of Angular/HTTP如何使用 Restler Rest 客户端库而不是 Angular/HTTP
【发布时间】:2017-05-18 22:25:22
【问题描述】:

我在 IONIC 项目上使用 Restler 库作为 Rest 客户端来使用 Notejs API, 目标是使用 Restler 而不是 Angularjs 的 Http 服务:

我试过这样:

let options = { headers: {'Authorization':[this.token]}};

restler.get('http://localhost:8083/api/auth/protected', JSON.stringify(options ) ).on('complete', function(result, response) {
    if (result instanceof Error) {
        reject(result);
    } else {
        resolve(result);
    }
});

这样返回:结果“未授权”

angular/Http方式:

let headers = new Headers();
headers.append('Authorization', this.token);

this.http.get('http://localhost:8083/api/auth/protected', {headers: headers})
         .subscribe(res => {
             resolve(res);
         }, (err) => {
             reject(err);
         });  

然后返回:{"_body":"{\"content\":\"Success\"}","status":200,"ok":true,"statusText":"OK","headers":{"Content-Type":["application/json; charset=utf-8"]},"type":2,"url":"http://localhost:8083/api/auth/protected"}

我已经尝试过 Restler get 方法来使用一个没有参数的 RESTful API 并且它可以工作,我认为参数选项(标题)没有正确传递

【问题讨论】:

  • 我认为最好的方法是为你的 http 请求创建一个拦截器并在那里设置标头(这样你就不必每次请求都这样做)
  • 看看你传递身份验证令牌的方式,在restler方式中你用一个数组来制作它,在ng2 http中你让它成为普通令牌。这就是恕我直言的区别。尝试更改它,一切都会正常工作。

标签: node.js angular rest http-headers


【解决方案1】:

我建议使用 needle 作为 Rest API 客户端,而不是使用 restler

我已经测试过了,效果很好,就像@angular/http 服务一样,

例如:

@angular/http 实现:

    return new Promise((resolve, reject) => {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post('http://localhost:8083/api/auth/login', JSON.stringify(credentials), {headers: headers})
      .subscribe(res => {

        resolve(data);

        resolve(res.json());
      }, (err) => {
        reject(err);
      });

       });

针实现:

    return new Promise((resolve, reject) => {

    let options = {
      headers: { 'Content-Type': 'application/json' }
    }

    needle.post('http://localhost:8083/api/auth/login', credentials, options, function(err, resp) {
    if (!err && resp.statusCode == 200){
                resolve(resp.body);
    }else{
      reject(err);

    }
    });

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 2019-04-21
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多