Get response headers for request created by browser - javascript

Suppose index.html has script which has url to external js file (example.js):
<html>
<head>
<script src="/example.js"></script>
</head>
<body></body>
</html>
What I have tried it's create XMLHttpRequest and than manually execute script with window.eval(request.responseText). Any other ways?

To get the response headers when you make a request to server:
Vanilla JS:
var client = new XMLHttpRequest();
client.open("GET", "/some_url", true);
client.send();
client.onreadystatechange = function() {
if (this.readyState == this.HEADERS_RECEIVED) {
console.log(client.getResponseHeader("some_header"));
}
}
jQuery:
$.ajax({
type: 'GET',
url: '/some_url',
success: function(data, textStatus, request) {
console.log(request.getResponseHeader('some_header'));
},
error: function(request, textStatus, errorThrown) {
console.log(request.getResponseHeader('some_header'));
}
});

Related

Consuming api using Javascript

I have been struggling to render a data object returned by an API request on an HTML page, however it keeps displaying the string object on the HTML page. Another problem is that I am not able to make use of the data object returned by the API request outside of the API function in Javascript. See the code below:
The API request, the console.log(data) outside the API function does not work
var params = {
// Request parameters
};
$.ajax({
url:
"https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
$.param(params),
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key",
"ef4ed92186214c868a59d97c3b353661"
);
},
type: "GET",
// Request body
data: "{body}",
})
.done(function (data) {
console.log(data);
document.getElementById("data").innerHTML = data.results;
})
.fail(function () {
alert("error");
});
});
console.log(data);
The HTML Page
<html>
<head>
<title>JSSample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="data"></div>
</body>
</html>
You need to pass in a callback function to handle the returned data.
function do_request(cb, cb_fail) {
var params = {};
$.ajax({
url:
"https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
$.param(params),
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key",
"ef4ed92186214c868a59d97c3b353661"
);
},
type: "GET",
// Request body
data: "{body}",
})
.done(cb)
.fail(cb_fail);
}
function cb(data) {
// you now have access to the data here
document.getElementById("data").innerHTML = JSON.stringify(data.results)
}
function cb_fail(error) {
console.log(error)
}
do_request(cb, cb_fail)

NodeJS: how to perform Ajax Post with FormData

I am testing a local HTML Form sending data to an aspx application as backend. Since I have some problem with CORS (even on localhost) I am trying to emulate the Ajax request performed by jQuery with NodeJS. I don't know if this is the right way to do. In the HTML form, after the jQuery validation, this is what I do:
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
console.log(response);
}
});
//console.log($(form).serialize())
}
and it works, until CORS ends the request. I mean that I can retrieve the data from the backend application.
Instead, if I do:
function loadDoc() {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
/*var FormData = require('form-data');
var myform = new FormData();
myform.append('firstname', 'foo');*/
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE", true);
//which is the same string I get from .serialize() in jQuery
xhttp.send("firstname=foo&email=some#domain.it");
}
loadDoc();
I cannot get anything from the server application. If I want to get the parameter firstname from the POST data, I get null. So, where am I wrong?
UPDATE
This is the only workaround I have found useful in NodeJS:
var http = require('http');
var querystring = require('querystring');
var post_data = querystring.stringify({'firstname':'Lory'});
var post_options = {
host: 'localhost',
port: '1308',
path: '/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
I had also tried with:
var request = require('ajax-request');
request.post({
url: 'http://127.0.0.1:1308/ImperoOrdini/ImperoOrdini.aspx?CMD=NUOVOORDINE',
data: {'firstname':'Lory'},
headers: {}
}, function(err, res, body) {
console.log(res);
}
);
but it did not work too. I feel such an ignorant and I would like to know the differences between those 3 libraries.
I have some doubts concerning the fact I must use querystring.stringify() in the working solution, because POST data are not in the URL and should not be uder the limits of query string, if I remember well.
I would like to suggest request module. while doing ajax call post, we can post the data by form or JSON format. It's based on receiver end point how they are receiving.
I hope you are trying to post form data.
var request = require('request');
request.post({
url:'http://service.com/upload',
form: {'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
If you are trying to do normal JSON post.
var request = require('request')
request({
method: 'POST',
uri: 'http://www.google.com',
body:{'firstname':'Lory'}
}, function(err,httpResponse,body){
/* ... */
})
request module provide lots of options. Play with that then you will get the better idea.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm" name="myForm">
<div>
<label for="comment">Comment:</label>
<textarea id="comment" name="comment"></textarea>
</div>
<div>
<label for="rating">Comment:</label>
<textarea id="rating" name="comment"></textarea>
</div>
<input type="submit" value="Submit!">
</form>
<script>
$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault();
//collect the form data using Id Selector what ever data you need to send to server
let comment=$('#comment').val();
let rating= $('#rating').val()
$.ajax({
url: 'replace your url',
data: JSON.stringify({"comment": comment, "rating": rating }),
processData: false,
type: 'POST',
contentType: 'application/json',
success: function (data) {
alert(data);
}
});
});
})
</script>
</html>

Unable to send cross-domain request in `Firefox` extension

I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
xhr.send();
JsonP
$.ajax({
type: 'GET',
url: "http://example.com/ajax.php?code=BSE",
dataType: "jsonp",
jsonpCallback: "jsonp_callback",
crossDomain: true,
success: function(res){
console.log(res);
}
});
Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.
And my php code:
PHP Code:
header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.
{
"manifest_version": 2,
"name": "web extension",
"version": "1",
"permissions": [
"http://example.com/"
],
"content_scripts": [
{
// ...
}
]
}
Try using new XDomainRequest() in your xhr request. XDomainRequest is an implementation of HTTP access control (CORS).
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://example.com/ajax.php?code=BSE';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send();

ajax request to Microsoft Emotion API in javascript

I am trying to try the microsoft emotion api. I am running a simple python web server with CORS enabled. Below is my server python file with which I start the server:
python-server.py
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
if __name__ == '__main__':
BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)
I have an index.html file in which I am sending the http request:
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",JSON.stringify({"my-key"}));
},
type: "POST",
// Request body
data: JSON.stringify({"url": "http://tinyurl.com/2g9mqh"}),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
After about 30 seconds I get the connection refused response. The http request code was taken from the emotion api's page I linked earlier. I wonder whether I need a real server or is there a mistake in the code? Thanks.
The JSON needs to be sent out as a string. So change your body specification to:
data: "{\"url\": \"http://...\"}"
Please use the code below(replace your-key), just save it as a .html and open it in the browser it shut work(without any server). If it works then try it in your python server.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","your-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Face API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key",
"");
},
type: "POST",
// Request body
data: JSON.stringify({
"url": "http://i1.mirror.co.uk/incoming/article6395000.ece/ALTERNATES/s1200/MAIN-David-Beckham-next-James-Bond.jpg"
}),
})
.done(function(data) {
console.log(data);
})
.fail(function(e) {
console.log(e);
});
});
</script>
</body>
</html>

Javascript won't do cross domain request from django

Hi here is an odd problem. I am trying to serve the below index.htm file with django. When you click the button, the page (not the server) does a cross-domain request. If I load the index file direct in a browser it works. However, if I serve it with django, I get "An error occurred trying to load the resource" in the same browser (Safari). I am using (YQL) this method for cross domain requests: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="/static/jquery-1.10.0.min.js"></script>
<script type='text/javascript' src="/static/jquery.xdomainajax.js"></script>
<script>
function myFunction()
{
$.ajax({
url: 'http://www.google.com',
type: 'GET',
success: function(res) {
var headline = $(res.responseText).text();
document.getElementById("demo").innerHTML=res;
},
beforeSend : function(xhr, settings) {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Cache-Control", "no-cache");
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
}
});
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>
Add the following code in your ajax function:
beforeSend : function(xhr, settings) {
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Cache-Control", "no-cache");
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
},
And also this function in your script:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
:D

Categories

Resources