【问题标题】:AngularJs custom headers with restful API GET method带有restful API GET方法的AngularJs自定义标头
【发布时间】:2015-04-19 12:49:40
【问题描述】:

我无法通过自定义标头连接到我的 API,当我在 google chrome 中运行应用程序时,我收到以下错误:

Remote Address:177.70.11.212:10
Status Code:401 Authorization Required
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, x-api-credencial, x-api-origem, x-api-token
Access-Control-Request-Method:GET
Connection:keep-alive
Host:api.repmais.com
Origin:http://evil.com/
Referer:http://localhost:8100/

我在网络表中看不到我的标题,我在这里缺少什么?

     angular.module('starter.services', [])


    .factory('ServiceClientes', ['$http', function ($http) {

        var endpoint = 'http://api.repmais.com/api/clients';

        var token = "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bFAcbFfd19MfacGf3FFm8CM1hG0eDiIk8";
        var credencial = "rm@w.com.br:cd87cd5ef753a06ee79fc75ds7cfe66c";
        var origem = "mobile";


         var config = {
        url: endpoint,
        method: 'GET',
        headers: {
            'X-API-TOKEN': token,
            'X-API-CREDENCIAL': credencial,
            'X-API-ORIGEM': origem
        }
    };


    return {

        getAll: function () {
            return $http(config);
        }
 }]);

app.js:

 .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.withCredentials = false;
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
    }
    ])

controller.js:

.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {

        ServiceClientes.getAll().success(function (data) {
            console.log(data);
        }).error(function (error) {
            console.log(error);
        });

【问题讨论】:

    标签: angularjs rest http-headers restful-authentication


    【解决方案1】:

    您只需将标头作为配置对象传递:

    var config = {
      url: endpoint,
      method: 'GET',
      headers: {
        'X-API-TOKEN': token,
        'X-API-CREDENCIAL': credencial,
        'X-API-ORIGEM': origem
      }
    }
    
    return $http(config);
    

    这应该会给你一个承诺,无论你在哪里调用你的端点,你都可以处理:

    ServiceClients.getAll().success(function () {
      // use your data
    }).error(function () {
      // handle error
    });
    

    【讨论】:

    • 感谢您的帮助,我已经更新了代码,现在我收到以下错误:GET localhost:8100/[object%20Object] 404 (Not Found)
    • 我看到您的代码已更新为使用 $http.get(config)。您不需要在其中添加“get”调用,该方法在配置对象中定义。就像 $http(config); 一样调用它或者,您可以使用快捷方式,请参见此处:stackoverflow.com/questions/11876777/…
    • 好的,我已经更新了问题,似乎没有通过标头,仍然获取 XMLHttpRequest 无法加载api。 repmais.com.br/api/cliente。无效的 HTTP 状态代码 401
    • 检查您的网络请求并查看您的标头是否存在。如果您的凭据无效,仍然可以返回 401 响应。
    • 我正在使用 Advanced Rest Client 来测试 API,它与该标头工作正常
    猜你喜欢
    • 2014-01-14
    • 2016-11-12
    • 2021-11-23
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2017-02-27
    相关资源
    最近更新 更多