I got a problem with the headers when i'm trying to do a POST Request with JSON
This is the code:
$.ajax({
type: "POST",
url: url,
data: jsonData,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
error: function(){
alert("Fail");
},
success: function(){
alert("Success");
}
});
And this are the Request Headers displayed by Firebug.
OPTIONS /path HTTP/1.1
Host: 192.168.15.109:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0 FirePHP/0.7.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
x-insight: activate
Pragma: no-cache
Cache-Control: no-cache
And the Response Headers:
HTTP/1.1 204 No Content
Date: Thu, 24 May 2012 19:17:01 GMT
Allow: OPTIONS,POST
As you can see, the headers doesnt match with the ones im specifying, but when i use CURL the Headers are this ones instead:
POST /path HTTP/1.1
User-Agent: curl/7.25.0 (i386-pc-win32) libcurl/7.25.0 OpenSSL/0.9.8u zlib/1.2
Host: localhost:8080
Accept: */*
Content-Type: application/json
Content-Length: 5
Any idea or solution for this?
I also modified JQuery Source to set default values of the Headers sent by Ajax to JSON, but didnt work.
Seems like a same-origin policy issue. Using dataType='jsonp' should work, but this might require other changes.
See https://developer.mozilla.org/en/http_access_control for an in-depth explanation.
Actually, it was a cross Domain problem, I defined my URL as an IP, so the browser interpreted it like a Cross Domain request.
Thanks for everything!
Related
I know there are many questions on SO about this but none of the suggestions have worked for me.
Here is my code:
var restService = "http://wcfrestservice:8004/RADPOCService/WebApp1";
$.ajax({
url: restService,
type: "POST",
data: { PhoneNumber: y },
dataType: "json",
contentType: "application/json; charset=utf-8",
success:
function (data) {
window.open(data.Url, '_blank');
}
});
Fiddler shows my request going across the wire like so (redacted):
POST http://localhost:8004/RADPOCService/WebApp1 HTTP/1.1
Host: localhost:8004
Connection: keep-alive
Content-Length: 22
Accept: application/json, text/javascript; q=0.01
Origin: http://localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:8000/Default.aspx
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Requestor: Me
PhoneNumber=1234567890
I am expecting the payload to look like this:
{ "PhoneNumber": "1234567890"}
When I set the payload as above in the Fiddler Composer tab the service works as expected. What am I doing wrong?
I hate to do this so quickly after posting my question but the answer is to use the JSON.stringify API on the data being sent to the service. So the above should have the following code for 'data' in the ajax call:data: JSON.stringify({ PhoneNumber: y })
I am trying to make CORS AJAX "GET" call to an web API service hosted in a test server. webAPI URL = http:xxx:xxx:xxx:xxx/api/v1/jobs
I have the following lines of code in WebAPIConfig.cs
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
AJAX request (from local)
$.ajax({
type: "GET",
datatype: "JSON",
url: http: xxx: xxx: xxx: xxx / api / v1 / jobs,
contentType: "application/json";
charset = utf - 8 ",
accept: 'application/json',
beforeSend: BH,
success: callback
}).done(function (data) {
var str = data.job_id + ': ' + data.job_name;
$('#responsevalue').text(str);
}).error(function (jqXHR, textStatus, errorThrown) {
$('#responsevalue').text(jqXHR.status + "::" + jqXHR.statusText + "::" + jqXHR.responseText );
});
In Fiddler, I can see the pre-flight request with OPTIONS being sent and the response with 200.
Fiddler Request Headers:
OPTIONS http:xxx:xxx:xxx:xxx/api/v1/jobs HTTP/1.1
Host: 50.17.211.226
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Fiddler Response Headers
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 14:21:50 GMT
Content-Length: 0
In Firebug, i can see the following details:
Firebug Request Headers:
OPTIONS http:xxx.xxx.xxx.xxx/api/v1/jobs HTTP/1.1
Host: xxx.xxx.xxx.xxx
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http:localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Firebug Response Headers:
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *, *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept, Content-Type
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 18:08:36 GMT
Content-Length: 0
I read lot of documentation here and in other places. It seems pretty simple and works for everyone (except me).
Final note: I tested the API with the html page residing in side the test server an it worked fine. Meaning the service and the web page both residing in the same domain.
Additional Info: Browser: Firefox, ASP.NET 4.5, web API 2.2, VS2013 Express
Thanks in advance and any help will be much appreciated.
In your response, it says the allowed headers are Content-Type, Accept, Content-Type, but you are asking for requestdateutc,requestverificationtoken. Try explicitly allowing those headers.
Hello I am trying to do a http request with Basic Auth, but I can't set the header authorization and it is allowed in server.
Ajax :
$.ajax({
xhrFields: { withCredentials: true },
beforeSend: function(xhr){xhr.setRequestHeader('authorization', 'Basic cmFmmFuQHBoaWlubm92YXRpb25zLmNv=');},
url : 'http://www.vozi.dev.br/api/audio',
type: 'POST',
data: JSON.stringify(sender),
dataType: 'json',
contentType: 'application/json',
success : function(data, textStatus, jqXHR) {
//do something
}
});
Http Request Header:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,pt;q=0.6
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:www.vozi.dev.br
Origin:http://localhost:8080
Referer:http://localhost:8080/act_text.jsp
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
Http Response Header:
Access-Control-Allow-Headers:accept, authorization, content-type
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
cache-control:no-cache
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Wed, 14 May 2014 20:15:53 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6 (Ubuntu)
Set-Cookie:PHPSESSID=k6gg748e47b2fv67; path=/
Transfer-Encoding:chunked
www-authenticate:Basic realm="Secured Area"
x-debug-token:5373cef9430fe
X-Powered-By:PHP/5.5.3-1ubuntu2
Error :
OPTIONS http://www.vozi.dev.br/api/audio 401 (A Token was not found in the SecurityContext.) jquery.js:8706
OPTIONS http://www.vozi.dev.br/api/audio Invalid HTTP status code 401 jquery.js:8706
XMLHttpRequest cannot load http://www.vozi.dev.br/api/audio. Invalid HTTP status code 401
I assume your having this issue with IE10 or IE11, This is not an issue with Chrome.
IE doesn't send authorization headers with OPTIONS request, so on server side if you enable Windows integrated authentication, it does reject the OPTIONS request.
I have this workaround posted on another stackoverflow question
I find out that i can't use
Access-Control-Allow-Origin:*
if I am using
withCredentials: true
Is necessary to set the origin.
We're experiencing some problems with some ajax calls. On the server side we're running Apache Tomcat with Servlets. On a few calls an Authorization (NTLM) is added in the request header,
and the post body is removed. We are using NTLM authentication on the site, but authentication is already done before these ajax calls are made, and this only happens on certain ajax calls.
Here the JavaScript making the Ajax call.
var postObjects = function(f, parameter, value, variables)
{
var post = {};
post['f']=f;
post['courseid']=trapi.courseID;
post['courseresourceid']=trapi.courseResourceID;
post['mode']=trapi.mode;
if(parameter!=null)
post['parameter']=parameter;
if(value!=null)
post['value']=value;
if(variables!=null)
{
for(var i=0; i<variables.length;i++)
{
post[variables[i][0]]=variables[i][1];
}
}
var returnString="";
$.ajax(
{
url : location.pathname,
data:post,
cache:false,
global:false,
dataType:'text',
contentType:'application/x-www-form-urlencoded; charset=UTF-8',
type:'POST',
async:false,
success: function(data)
{
returnString=data;
},
error: function(jqXHR, textStatus,errorThrown)
{
returnString="Error: "+textStatus;
}
});
return returnString;
}
And here is info from fiddler about a POST made by the postObjects function which adds NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
Authorization: NTLM BASE64ENCODEDSTRING
Content-Length: 0
And here is info from fiddler about a POST made by the same postObjects function not adding NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 61
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
f=getlasterror&courseid=909&courseresourceid=4079&mode=normal
Do I have to re-authenticate each time this happens?
I am creating an ajax call like so:
var form = $("#form");
$.ajax({url: "/url/create_web_registration?invite_token=abc",
data: form.serialize(),
type: "POST",
dataType: "json",
success: $.web_registration.index.registerSubmitSuccess,
error: $.web_registration.index.registerSubmitError,
});
However when I repeat the request with identical parameters, I sometimes get the success callback and sometimes get the error callback. When the error callback is called, the jqXHR.status is always 0 on a failure, but there is nothing descriptive in statusText, responseText, textStatus or errorThrown.
I did a tcpdump on the HTTP requests and the request looks like:
POST /shopkick/v1/user/create_web_registration?invite_token=abc HTTP/1.1
Host: [redacted]:5000
Connection: keep-alive
Referer: http://[redacted]:5000/wr2/abc?invite_token=&zip_code=94123&phone_number=%2B16785556982&facebook-form=
Content-Length: 169
Origin: http://[redacted]:5000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/javascript, */*; q=0.01
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
invite_token=&zip_code=94123&phone_number=%2B16785552982
The response looks like:
HTTP/1.0 200 OK
Server: PasteWSGIServer/0.5 Python/2.6.1
Date: Wed, 31 Aug 2011 05:34:10 GMT
Pragma: no-cache
Cache-Control: no-cache
Content-type: text/plain
Content-Length: 74
{"error_message": "Facebook account already registered", "success": false}
I am at a loss to why it is sometimes succeeding and sometimes failing.
The problem was I was using ajax to submit a form. When I clicked the submit button it would work fine, but when I hit enter in a text input field it would encounter the errors. Apparently hitting enter in a input field was causing the form to submit twice. The fix was to set onsubmit="return false;" for the form to prevent double submission.