我无法传递自定义标头以连接到我的API,当我在谷歌浏览器中运行应用时,我收到以下错误:
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);
});
答案 0 :(得分: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
});