control:no-cache` field into my request when requesting RSS feed
I cant quit figure what values should i put in
In case of Content-type it works well but it refuses to add correctly Cachce-Control
code :
options = {uri :SUPPORT_FEED_URI,
headers : {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
}
request.get(options)
.on('error', (err) => { reject(err); })
.pipe(feedparser)
.on('end', () => { return resolve(items); });
What i get in request headers :
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:cache-control <-- doesnt seems to be right Want something like Cache-Control : no-cache
Access-Control-Request-Method:GET
Connection:keep-alive
Host: xxxx.yyyy.zz
Origin:http://127.0.0.1:8888
Referer:http://127.0.0.1:8888/webconsole/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
content-type:application/x-www-form-urlencoded
Your capture is a CORS pre-flight (OPTIONS) request as the URL is on a different domain or considered to be different-origin.
Such a request will not include custom headers, they are added to Access-Control-Request-Headers instead to see if the destination server will allow them.
If the destination server responds with an acceptable allow- response the subsequent GET will include your header.
Depends what you are trying to achieve.
If you are trying to force a non-cached response and dont have control over the server, one thing you can do is to add a fake query param like this.
options = {
uri :`${SUPPORT_FEED_URI}?${new Date().getTime()}`,
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
},
}
For more information on the 'Cache-Control' header see the top answer here.
What's the difference between Cache-Control: max-age=0 and no-cache?
Related
I'm making an api that communicates with a website to pull player statistics. I've made multiple POST/GET HTTP/1 requests to the server to get a session token and player ID. I then use those values(valid values which I have tested before passing to my function) in my last function to fetch player statistics. The last request is a HTTP/2 GET request. I'm using the got library and vanilla Node. Here is my request:
//THESE ALL HAVE SOME VALUE AFTER I USE SOME OF MY FUNCTIONS; THE FUNCTION I'M
//HAVING TROUBLE WITH IS THE LAST FUNCTION AND IS PASSED VERIFIED NON-NULL VALUES
var session = {
app_id: '3587dcbb-7f81-457c-9781-0e3f29f6f56a',
space_id: '5172a557-50b5-4665-b7db-e3f2e8c5041d',
session_id: null,
ticket: null,
};
var player = {
name: null,
id: null,
platform: 'uplay',
kills: null,
deaths: null,
rank: null,
};
async function get_player_stats(session, player) {
var platform = 'PC';
if (player.platform === 'uplay') {
platform = 'PC';
}
var options = {
':authority': 'r6s-stats.ubisoft.com',
':method': 'GET',
':path': `/v1/current/operators/${player.id}?gameMode=all,ranked,casual,unranked&platform=${platform}&teamRole=attacker,defender&startDate=20200723&endDate=20201120`,
':scheme': 'https',
'authorization': `ubi_v1 t=${session.ticket}`,
'ubi-appid': session.app_id,
'ubi-sessionid': session.session_id,
'content-type': 'application/json',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36',
}
const url = `https://r6s-stats.ubisoft.com/v1/current/operators/${player.id}?gameMode=all,ranked,casual,unranked&platform=${platform}&teamRole=attacker,defender&startDate=20200723&endDate=20201120`;
try {
const response = got(url, {headers: options, http2: true});
console.log(response);
}
catch (err) {
console.log(err);
}
}
//FUNCTION CALL
async function fetch(user) {
var stats_string = await get_player_stats(session, player);
console.log(stats_string);
}
fetch(username);
Chrome's request header from network log:
:authority: r6s-stats.ubisoft.com
:method: GET
:path: /v1/current/operators/e96ae749-8939-43ed-895f-bf1817e849d9?gameMode=all,ranked,casual,unranked&platform=PC&teamRole=attacker,defender&startDate=20200723&endDate=20201120
:scheme: https
accept: */
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: ubi_v1 t= LONG TOKEN
dnt: 1
expiration: 2020-11-21T09:13:54.804Z
origin: https://www.ubisoft.com
referer: https://www.ubisoft.com/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
ubi-appid: 3587dcbb-7f81-457c-9781-0e3f29f6f56a
ubi-sessionid: d78f3306-0e5c-4ac8-ad63-5a711b816f76
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36
Chrome's Response header from network tools:
access-control-allow-credentials: true
access-control-allow-origin: https://www.ubisoft.com
content-encoding: gzip
content-length: 16969
content-type: application/json
date: Sat, 21 Nov 2020 06:14:47 GMT
status: 200
vary: Origin
What I've tried:
I've tried just about everything. I've googled what causes 400 errors, which apparently are mostly user error, and I've looked through my code for days and also looked at Chrome's network activity. I've tried matching Chrome's request header with mine to no avail(my header variable is one of many iterations I've tried--pretty sure I've tried every combination of possible headers). However, sometimes I'll get 400 bad error, or an invalid header response from the server. I've tried using the vanilla Node http2Client.request and that gives me an invalid header/400 as well.
Okay, finally figured out why this wasn't working. I missed one tiny line in what I thought I already tried millions of times.
In the request header on the Chrome Network activity there is a field for expiration.
I needed to set the expiration value in the header to get the data.
So the value I needed to add to my header in my code was:
expiration: 2020-11-21T09:13:54.804Z
Future edit: The expiration is the date in ISO format. You can make a date Object and convert to ISO:
var time = new Date();
var expiration = time.toISOString();
function someRequest() {
var options = {
'expiration': expiration,
}
}
I am trying to do a fetch() post and send a FormData object and an Int. I can do one or the other but when trying to send both I get unrelating 415 status codes.
My post data looks like:
var payload = {
documents: documents, // which is of type new FormData()
applicationId: applicationId // which is of type int
}
method: "POST",
headers: {
"Authorization": `Bearer ${accessToken}`
},
body: payload
And my c# backend looks like below:
[HttpPost]
public async Task<JsonResult> UploadDocuments(DocumentUploadVm payload)
below is my request headers:
:authority: localhost:44343
:method: POST
:path: /api/expert/UploadDocuments
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: Bearer eyJraWQiOiJYNnplamszSy10RjBkMmtWYXpHNE84aFNsUGtSSklhT1ZMeGQ3dC1tQ21FIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULnRuaGFQVGp5RnY4eEhMaGFVM18zLW5rdlVLWV9QUEw5aXJTczI4NHF3c3ciLCJpc3MiOiJodHRwczovL2Rldi04NzAzMTAub2t0YS5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiJhcGk6Ly9kZWZhdWx0IiwiaWF0IjoxNjAwNjQ0MzAzLCJleHAiOjE2MDA2NDc5MDMsImNpZCI6IjBvYXAzbmdtNG1BUDBTT1YzNHg2IiwidWlkIjoiMDB1ZGFudnVpUjB6SHp6emk0eDYiLCJzY3AiOlsicHJvZmlsZSIsImdyb3VwcyIsImVtYWlsIiwib3BlbmlkIiwicGhvbmUiXSwic3ViIjoiZGFuaWVsOTVicm93bkBnbWFpbC5jb20ifQ.0ya1CTLuPQcPLyXgph7TQMzwhWtUWrb1QzQx6G2kS4X5fawXZ13XFIztG2TMjCIrTrbGa1WPx-hYmqI7EB2Eilhp0ekQKt85U7Q3Ug5HuQQMhrH8KjvHF5fhElNwf5z1vp4Zgtg1MbF-MPetoV4ttG3SQwxLJ-SFHZFkA-HY2lzoMQS-40V53q5ruVbeXEpX8iwhSXzA7mp53YEaSNWecDJxHoBy6yXszrJrpkQ1wqsp9p5ti1XASVczlLkL-J-IOx6Rf61LfPH9_Q4KR3aZsd_peInJF14YF0lLesmxcnQcvbdMGsUO0PrPtku8wQEeuuQGYn-zZR5eBSDR9ZbzLw
content-length: 15
content-type: text/plain;charset=UTF-8
origin: http://localhost:8080
referer: http://localhost:8080/expert/register
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36
I have tried using the [FromBody],[FromForm] tags, stringifying and everything in between to no avail. Any help would be greeeeeeeatly appreciated as I am losing my mind.
I send an AJAX post request in angularjs but it send nothing, since I check on the server side what has arrived which prints nothing using :
print_r($_REQUEST);
However when I use:
print_r(json_decode(file_get_contents("php://input")));
It works since I know the data are sent in JSON chunk and not regular form-format.
Now I have figured out how to send the post data with a header similar to that of jQuery but I still get nothing in server side using regular $_REQUEST or $_POST.
Here is the code block written in Javascript. It is worth mentioning:
I have checked all the data of the inputs using console.log() and all of them are defined.
checkUserPostData = { "username" : registerUsername, "username_check" : 'true'};
$http.post("server.php",
checkUserPostData, {"headers" :
{ "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }} )
.success(function(data, status, header, config){
console.log(data);
/*
if(data=='exists')
return true;
else return false;*/
})
.error(function(data, status, header, config){
console.log("error: "+data);
return data;
}); // end of $http request
} // end of CheckUser()
Here is also a log of chrome console on ajax request sent:
Remote Address:::1:8080
Request URL:http://localhost:8080/app/server.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:44
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/app/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Form Dataview sourceview URL encoded
{"username":"asdsa","username_check":"true"}:
Response Headersview source
Connection:Keep-Alive
Content-Length:1231
Content-Type:text/html
Date:Tue, 27 May 2014 12:16:13 GMT
Keep-Alive:timeout=5, max=98
Server:Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16
X-Powered-By:PHP/5.4.16
I have a Rails service returning data for my AngularJS frontend application. The service is configured to allow CORS requests by returning the adequate headers.
When I make a GET request to receive data, the CORS headers are sent, as well as the session cookie that I have previously received on login, you can see for yourself:
Request URL:http://10.211.194.121:3000/valoradores
Request Method:GET
Status Code:200 OK
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:_gestisol_session=BAh7B0kiDHVzZXJfaWQGOgZFRmkASSIPc2Vzc2lvbl9pZAY7AEZJIiVmYTg3YTIxMjcxZWMxNjZiMjBmYWZiODM1ODQzMjZkYQY7AFQ%3D--df348feea08d39cbc9c817e49770e17e8f10b375
Host:10.211.194.121:3000
Origin:http://10.211.194.121:8999
Pragma:no-cache
Referer:http://10.211.194.121:8999/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin
Access-Control-Allow-Methods:GET,POST,OPTIONS
Access-Control-Allow-Origin:http://10.211.194.121:8999
Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:5389
Content-Type:application/json; charset=utf-8
Date:Mon, 04 Nov 2013 14:30:51 GMT
Etag:"2470d69bf6db243fbb337a5fb3543bb8"
Server:WEBrick/1.3.1 (Ruby/1.9.3/2011-10-30)
X-Request-Id:15027b3d323ad0adef7e06103e5aa3a7
X-Runtime:0.017379
X-Ua-Compatible:IE=Edge
Everything is right and I get my data back.
But when I make a POST request, neither the CORS headers nor the session cookie are sent along the request, and the POST is cancelled at the server as it has no session identifier. These are the headers of the request:
Request URL:http://10.211.194.121:3000/valoraciones
Request Headers
Accept:application/json, text/plain, */*
Cache-Control:no-cache
Content-Type:application/json;charset=UTF-8
Origin:http://10.211.194.121:8999
Pragma:no-cache
Referer:http://10.211.194.121:8999/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{valoracione:{revisiones_id:1, valoradores_id:1}}
valoracione: {revisiones_id:1, valoradores_id:1}
And the service answers with a 403 because the request does not contain the session cookie.
I don't know why the POST request fails, as the $resource is configured just like the other one and I have defined the default for $httpProvider to send the credentials (and it works right as the GET request succeeds):
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}])
This is the failing resource when I call $save() on an instance:
'use strict';
angular.module('gestisolApp')
.service('ValoracionesService', ['$resource', 'API_BASE_URL', function ValoracionesService($resource, API_BASE_URL) {
this.valoraciones = $resource(API_BASE_URL + '/valoraciones');
}]);
And this is the service that succeeds with the query() call:
'use strict';
angular.module('gestisolApp')
.service('ValoradoresService', ['$resource', 'API_BASE_URL', function ValoradoresService($resource, API_BASE_URL) {
this.valoradores = $resource(API_BASE_URL + '/valoradores');
}]);
They are much like the same.
Does anybody know why the POST is sent without the session cookie?
Edit
Just to complete the information, preflight is handled by the following method, and is handled OK as the request before the failing POST is an OPTIONS that succeeds with a 200 response code:
def cors_preflight_check
headers['Access-Control-Allow-Origin'] = 'http://10.211.194.121:8999'
headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin'
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '1728000'
render :nothing => true, :status => 200, :content_type => 'text/html'
end
This is the CORS OPTIONS request/response exchange previous to the failing POST:
Request URL:http://10.211.194.121:3000/valoraciones
Request Method:OPTIONS
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, x-requested-with, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:10.211.194.121:3000
Origin:http://10.211.194.121:8999
Referer:http://10.211.194.121:8999/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin
Access-Control-Allow-Methods:GET,POST,OPTIONS
Access-Control-Allow-Origin:http://10.211.194.121:8999
Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:1
Content-Type:text/html; charset=utf-8
Date:Mon, 04 Nov 2013 15:57:38 GMT
Etag:"7215ee9c7d9dc229d2921a40e899ec5f"
Server:WEBrick/1.3.1 (Ruby/1.9.3/2011-10-30)
X-Request-Id:6aa5bb4359d54ab5bfd169e530720fa9
X-Runtime:0.003851
X-Ua-Compatible:IE=Edge
Edit 2: I have changed the title to reflect clearly my problem
I had a similar problem and adding the following before angular $http CORS request solved the problem.
$http.defaults.withCredentials = true;
Refer https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Requests_with_credentials for more details.
When CORS is involved, then your browser will send an OPTIONS request before the POST request.
I don't know the specifics with Rails, but I guess you have to configure Rails to actually answer the OPTIONS request with the adequate CORS headers.
The following code is just for comparison - it shows how you would address the issue in Java:
public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Access-Control-Allow-Origin", "http://10.211.194.121:8999");
resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST, GET");
resp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin");
resp.setHeader("Access-Control-Max-Age", "600");
resp.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
super.doOptions(req, resp);
}
But it might get you on the right track how to configure it in Rails.
Ok, finally I figured out what was happening.
By the answer posted on this question, I removed the HttpOnly parameter from the cookie and got it working on Firefox. Later for Chrome was just a matter of applying the rest of recommendations from the answer to make it work, like setting a domain for the cookie.
I am a novice to angular.js, and I am trying to add some headers to a request:
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
};
$http.get('https://www.example.com/ApplicationData.svc/Malls(1)/Retailers', config).success(successCallback).error(errorCallback);
I've looked at all the documentation, and this seems to me like it should be correct.
When I use a local file for the URL in the $http.get, I see the following HTTP request on the network tab in Chrome:
GET /app/data/offers.json HTTP/1.1
Host: www.example.com
Connection: keep-alive
Cache-Control: max-age=0
If-None-Match: "0f0abc9026855b5938797878a03e6889"
Authorization: Basic Y2hhZHN0b25lbWFuOkNoYW5nZV9tZQ==
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
If-Modified-Since: Sun, 24 Mar 2013 15:58:55 GMT
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
X-Testing: Testing
Referer: http://www.example.com/app/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
As you can see, both of the headers were added correctly. But when I change the URL to the one shown in the $http.get above (except using the real address, not example.com), then I get:
OPTIONS /ApplicationData.svc/Malls(1) HTTP/1.1
Host: www.datahost.net
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://mpon.site44.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Access-Control-Request-Headers: accept, origin, x-requested-with, authorization, x-testing
Accept: */*
Referer: http://mpon.site44.com/app/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
The only difference in code between these two is one is for the first the URL is a local file, and for the second the URL is a remote server. If you look at the second Request header, there is no Authentication header, and the Accept appears to be using a default instead of the one specified. Also, the first line now says OPTIONS instead of GET (although Access-Control-Request-Method is GET).
Any idea what is wrong with the above code, or how to get the additional headers included using when not using a local file as a data source?
I took what you had, and added another X-Testing header
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose',
"X-Testing" : "testing"
}
};
$http.get("/test", config);
And in the Chrome network tab, I see them being sent.
GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.
Basic authentication using HTTP POST method:
$http({
method: 'POST',
url: '/API/authenticate',
data: 'username=' + username + '&password=' + password + '&email=' + email,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Login-Ajax-call": 'true'
}
}).then(function(response) {
if (response.data == 'ok') {
// success
} else {
// failed
}
});
...and GET method call with header:
$http({
method: 'GET',
url: '/books',
headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json',
"X-Login-Ajax-call": 'true'
}
}).then(function(response) {
if (response.data == 'ok') {
// success
} else {
// failed
}
});
If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common = {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
};
}]);
my suggestion will be add a function call settings like this
inside the function check the header which is appropriate for it. I am sure it will definitely work. it is perfectly working for me.
function getSettings(requestData) {
return {
url: requestData.url,
dataType: requestData.dataType || "json",
data: requestData.data || {},
headers: requestData.headers || {
"accept": "application/json; charset=utf-8",
'Authorization': 'Bearer ' + requestData.token
},
async: requestData.async || "false",
cache: requestData.cache || "false",
success: requestData.success || {},
error: requestData.error || {},
complete: requestData.complete || {},
fail: requestData.fail || {}
};
}
then call your data like this
var requestData = {
url: 'API end point',
data: Your Request Data,
token: Your Token
};
var settings = getSettings(requestData);
settings.method = "POST"; //("Your request type")
return $http(settings);
What you see for OPTIONS request is fine. Authorisation headers are not exposed in it.
But in order for basic auth to work you need to add: withCredentials = true; to your var config.
From the AngularJS $http documentation:
withCredentials - {boolean} - whether to to set the withCredentials
flag on the XHR object. See requests with credentials for more
information.
And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.
In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.
The way you are adding headers is the right way to do it.
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to
send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted. It sets
custom headers in the request (e.g. the request uses a header such as
X-PINGOTHER)
Ref: AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?
You are just adding a header which server does not allow.
eg - your server is set up CORS to allow these headers only (accept,cache-control,pragma,content-type,origin)
and in your http request you are adding like this
headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json',
'x-testing': 'testingValue'
}
then the Server will reject this request since (Authorization and x-testing) are not allowed.
This is server side configuration.
And there is nothing to do with HTTP Options, it is just a preflight to server which is from different domain to check if server will allow actual call or not.
For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?
{
headers: {
Authorization: "Basic " + getAuthDigest(),
Accept: "text/plain"
}
}
I'm using $http.ajax(), though I wouldn't expect that to be a game changer.