I send an octet-stream via ajax to my PHP server. I want to receive it as the octet stream and decode it, not as a string. The thing is that the request body is a string, and it seems that ajax sends it as plain text, even though I have overriden the mime type. This is my ajax:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
};
xmlhttp.open("POST", "something.php", true);
xmlhttp.overrideMimeType("application/octet-stream");
xmlhttp.send(stream); // some array buffer
The request headers:
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:80
Response Headers
view source
Connection:Keep-Alive
Content-Length:175
Content-Type:application/octet-stream
Date:Sat, 30 Apr 2016 17:07:04 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.18 (Win32) OpenSSL/1.0.2e PHP/7.0.4
X-Powered-By:PHP/7.0.4
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:160
Request Payload
#9a54dbc4bdd16c1a19804751d113c44b#Some very boring string here :)
So the mime type is octet-stream, but the request payload is a string. What's wrong?
Related
I'm performing a request via Javascript to a server using the following code:
<script>
(function() {
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "http://remoteurltobecalled");
if (request) {
request.onload = function () {
if (request.readyState == request.DONE) {
if (request.status == 200) {
var text = request.responseText;
alert(text);
}
}
}
request.onerror = function () {
alert('status:'+request.status);
alert('statusText: '+request.statusText);
alert('responseText: ' + request.responseText);
alert('responseBody: ' + request.responseBody);
alert('Woops, there was an error making the request.');
};
var response=request.send();
}
})();
</script>
Using Fiddler i can see that the response from the server is:
HTTP/1.1 200 OK
Date: Wed, 21 Jun 2017 09:20:55 GMT
Server: Apache/2.4.7 (Ubuntu)
Set-Cookie: JSESSIONID=9A78296BD30D8AA45C1B4DF467118309; Path=/PATHREQUESTED
Vary: Accept-Encoding
Content-Length: 19982
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=ISO-8859-1
And then there's the body of the response.
Anyway, the response in the javascript code is an error, with status 0 and responseText and responseBody are empty. How could i get the full response provided by the server? is it a CORS issue?
I followed this article to connect to Azure via Rest where the first step is to get an access-token for the service. So i tried to send the following request:
POST https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: wamsprodglobal001acs.accesscontrol.windows.net
Content-Length: 120
Expect: 100-continue
Connection: Keep-Alive
Accept: application/json
grant_type=client_credentials&client_id=ams_account_name&client_secret=URL_encoded_ams_account_key&scope=urn%3aWindowsAzureMediaServices
and replaced the client_id and key(encoded) in the data to be posted.
But Chrome promptly complains about setting the unsafe Host-, Content-Length-, Connection- and Expect-Headers. So i omitted those and end up with the following:
xhr = new XMLHttpRequest();
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.send("grant_type=client_credentials&client_id=<id>&client_secret=<encodedSecret>scope=urn%3aWindowsAzureMediaServices");
now upon sending the request i get:
XMLHttpRequest cannot load https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://nope.com' is therefore not allowed access.
But the request works when i send it through the Rest Client, Fiddler and requestmaker.com which i take as evidence that the request is formed correctly ...
Any hint as to how i can get this to work would be greatly appreciated.
Try the following (generated from POSTMAN)
var data = "grant_type=client_credentials&client_id=<ACOUNTNAME>&client_secret=<ACCOUNTKEY>&scope=urn%3AWindowsAzureMediaServices";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("host", "wamsprodglobal001acs.accesscontrol.windows.net");
xhr.setRequestHeader("connection", "Keep-Alive");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
In Postman, i have to have the Interceptor plugin enabled for this to work though, and disable Automatically Follow Redirects. See if that helps at all.
After you get the response back and parsed the access_token, you can use it in the next call to get the closest API endpoint like this
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://media.windows.net/");
xhr.setRequestHeader("x-ms-version", "2.11");
xhr.setRequestHeader("authorization", "Bearer <ACCESS_TOKEN>");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
I'm trying to make a XMLHttpRequest to a server, the server accepts JSON as arguments and it's supposed to register the arguments I'm sending.
Here's my code:
function makeXMLRequest() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://mywebserverhere/register", true);
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "POST, GET");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status != 200) {
// Error
return;
}
alert(xmlhttp.responseText);
}
xmlhttp.send({"name": "pedro21", "pass": "nAosei1"});
}
But I get this error:
XMLHttpRequest cannot load http://mywebserverhere/register. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
Any ideas?
To allow CORS in a POST request you need to make a header. With GET you don't must to put this, but with POST you need:
xmlhttp.setRequestHeader('X-PINGOTHER', 'pingpong');
I started developing a webinterface with bootstrap and so I used javascript to receive some JSON-Data.
My JSON-String is build with JSONObjects in JAVA and I used Jersey RestFUL-Service.
Java Code:
#GET
#Path("test")
#Produces(MediaType.TEXT_HTML)
public String createTestJson(){
JSONObject jsobject= new JSONObject();
try {
jsobject.append("test1", "test");
jsobject.append("test2", "test");
jsobject.append("test3", "test");
jsobject.append("test4", "test");
jsobject.append("test5", "test");
jsobject.append("test6", "test");
jsobject.append("test7", "test");
}catch(Exception e){
e.printStackTrace();
}
return jsobject.toString();
}
When I call the URL with the browser it works:
{"test1":["test"],"test2":["test"],"test3":["test"],"test4":["test"],"test5":["test"],"test6":["test"],"test7":["test"]}
I created a JavaScript function, which should retrieve the JSON String and fill the certain values in my HTML-page.
function loadJSON()
{
var data_file = "http://127.0.0.1:8085/Rest/test/test";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
alert(http_request.responseText.length);
var jsonObj = JSON.parse(http_request.responseText);
document.getElementById("test1").innerHTML = jsonObj.test1;
document.getElementById("test2").innerHTML = jsonObj.test2;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
When I analyse the document with firebug, I can see that the GET- inquiry is completed and it's state is "200 OK". The answer of the inquiry is the JSON String.
I also analysed the script and it seems to stop working at:
var jsonObj = JSON.parse(http_request.responseText);
Additionally I wrote out the length of the responseText and the result is "0".
So I really don't get the problem. According firebug the script gets the data, but it breaks down at parsing the JSON String. It could relate to the responseText, which has a length of 0.
-------Edit-----
More Firebug information:
The XMLHTTPRequest-Object Data after receiving the data:
DONE 4
HEADERS_RECEIVED 2
LOADING 3
OPENED 1
UNSENT 0
mozAnon false
mozBackgroundRequest false
mozSystem false
onloadend null
ontimeout null
readyState 1
response ""
responseText ""
responseType ""
responseXML null
status 0
statusText ""
timeout 0
The inquiry-header
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Host 127.0.0.1:8085
Origin null
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
The response-header
Content-Type application/xhtml+xml
Date Mon, 24 Aug 2015 22:56:18 GMT
Server Apache-Coyote/1.1
Transfer-Encoding chunked
Response:
{"test1":["test"],"test2":["test"],"test3":["test"],"test4":["test"],"test5":["test"],"test6":["test"],"test7":["test"]}
Maybe you can help me!
Thank you!
Marko
I would be interested if your JSON is recieved as type="application/json or perhaps as XML/HTML. Could it be that the response is XML and so the "object" is stored inside http_request.XML?
---------- EDIT ----------
I think you are having issues with the Same-Origin-Policy of JS. You cannot load your field because of that. Try to implement your JS inside a view of your Java-App (so that you can access it via http:// and in the same domain as your app) and try it again.
I attempting to download an excel file and check it before sending it on to the user. When I set a breakpoint on var response - oReq.response, I see that oReq.response is null. When I check my network tab, I see that the response is not null rather it is the excel file as expected. Why doesn't the excel file come through to the callback?
var oReq = new XMLHttpRequest();
oReq.open("GET", service, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var response = oReq.response;
if (response === parseInt(response, 10)) {
alert("That query had no results");
$("#dialog").dialog("close");
}
else {
var blob = new Blob([response], { type: "application/vnd.ms-excel" });
var objectUrl = URL.createObjectURL(blob);
window.location = objectUrl;
//saveAs(blob, 'Ad_Hoc_Results.xls');
$("#dialog").dialog("close");
}
};
oReq.send();
Response Headers:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Disposition:attachment; filename=AdHocReport.xls
Content-Length:6656
Content-Type:application/vnd.ms-excel
Date:Mon, 20 Jul 2015 19:56:50 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcRGV2XE5KVEFcTGFuZUNsb3N1cmVBcGlcYXBpXHJlcG9ydFxHZXRBZEhvY1F1ZXJ5UmVwb3J0?=