简体   繁体   中英

XMLHttpRequest cannot load URL Invalid HTTP status code 401 AngularJs

I'm trying to get some data from an API using angular.js and in google chrome app - Advanced Rest Client I tested the headers and it is working fine, I get a 200 response and I can see the data, but when I run my app I get the following error:

Refused to set unsafe header "Access-Control-Request-Headers" ionic.bundle.js:17607 OPTIONS http://api.representemais.com.br/api/clientes 401 (Authorization Required) (index):1 XMLHttpRequest cannot load http://api.representemais.com.br/api/clientes . Invalid HTTP status code 401

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

    /* CATEGORIES */
    .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";


        return {

            getAll: function () {
                return $http.get(endpoint, {
                    headers: {

                    'X-API-TOKEN': token,
                    'X-API-CREDENCIAL': credencial,
                    'X-API-ORIGEM': origem,
                    'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
                    'Access-Control-Allow-Origin' : 'http://localhost:8100',
                    'Access-Control-Allow-Credentials': true,
                    'Access-Control-Request-Headers': 'X-Requested-With, accept, content-type',
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                    }
                });
            }
 }]);

You are trying to manually set headers that are supposed to be set by the browser.

The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent.

https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Also, the Access-Control-Allow headers are supposed to be used by servers. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

 $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};

add that to your app.config, if that doesn't work, try posting the request from the controller no from the service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM