xmlhttp request status 302 - javascript

I am trying to write core java script application that can test and analyse the http request. I started with below code. Firebug net tab says 302 status error.
<script type="text/javascript">
$(document).ready(function(){
var req = new XMLHttpRequest();
req.open("GET","http://www.google.com",true);
req.onreadystatechange = statusListener;
req.send(null);
});
function statusListener(req){
if (req.readyState == 4)
{
if (req.status == 200) {
var docx=req.responseXML;
console.log(docx);
}
}
}
</script>

3xx status codes are redirections.
302 means "Found". Quote from w3.org:
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.
If you want to get the page it redirects to, you have to check the URI in the response headers with the getResponseHeader() method.
You can see here to see how to access the correct URI.

Related

Access-Control-Allow-Origin' header contains multiple values 'http://xx.xx.xx.xx:3002, http://xx.xx.xx.xx:3002', but only one is allowed

I have downloaded a windows executable file and I installed it. The service will be listening on localhost:11100 port.
I have a written a javascript code to connect to the port and running this javascript code on any webserver is failing, because server sending multiple Access-Control-Allow-Origin headers in the response.
But if I write my JavaScript code in plain html page locally and open it in browser then it is sending one 'Access-Control-Allow-Origin' in the response.
Below is the Javascript code:
function RDService(){
var url = "http://127.0.0.1:11100";
var xhr;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number{
//IE browser
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//other browser
xhr = new XMLHttpRequest();
}
xhr.open('RDSERVICE', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
var status = xhr.status;
if (status == 200) {
alert(xhr.responseText);
//Capture(); //Call Capture() here if FingerPrint Capture is required inside RDService() call
console.log(xhr.response);
} else {
console.log(xhr.response);
}
}
};
xhr.send();
}
after calling the RDService function below error is throwing by the service:
Failed to load http://127.0.0.1:11100/: Response to preflight request
doesn't pass access control check: The 'Access-Control-Allow-Origin'
header contains multiple values 'http://xx.xx.xx.xx:3002,
http://xx.xx.xx.xx:3002', but only one is allowed. Origin
'http://xx.xx.xx.xx:3002' is therefore not allowed access.
The windows executable should only be returning one domain or * in the Access-Control-Allow-Origin header. This is not an issue with the client side JavaScript.
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: <origin>
*
For requests without credentials, the server may specify "*" as a wildcard, thereby allowing any origin to access the resource.
<origin>
Specifies a URI that may access the resource.
reference:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Ajax request with JavaScript responds with 302 (Found)

I am trying to send data by Ajax with the Post method, but the answer gives me 302 (Found) and I do not know what it can be. This is my code:
function sendData(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log("Response" + xmlhttp.responseText);
}
}
xmlhttp.open("POST", "request.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+document.getElementById('username').value);
}
and my .php file only print a message
<?php echo 'hello : ' . $_POST["name"] ?>
The 302 status code indicates that the resource you are requesting has redirected to another resource. If this is behind some authentication, or requiring a session to be active then yes, it would follow that the session timing out is responsible for the ajax resource being called to redirect to possibly a login screen maybe.
Try to use jQuery request, as it much simpler - also recommended in the above comments!
One way to get such a message is, to forget to add a / to the end of a URL, which is a "sub-directory" of the document root. As the URL your.domain/whatever and your.domain/whatever/ might not be the same. (Depending on server configuration, and the actual application serving those URLs.)
I can see, in this case you are actually POSTing to /request.php, so this might not apply, but just in case, I'd try to make that request 'by hand' and see what happens.
There are many browser plugins, that let you generate AJAX queries.

MailChimp API 3.0 xhr subscribe 501 error

I am trying to subscribe users to my mailchimp list using this snippet:
function subscribeUser(name, email) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/';
var data = {};
data.email_address = email;
data.status = "subscribed";
data.merge_fields = {};
data.merge_fields.NAME = name;
xhr.open("POST", endpoint, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "apikey <key>");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(data);
}
It generates this error in chrome:
I am unable to write ajax based services to update lists. Because you guys did not add the Access Control header. I cannot send a simple xhr to your endpoint using a modern browser.
XMLHttpRequest cannot load https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
Mine is a static website and I would like to keep it that way. No backend is needed, hosted on github. So I need a JS solution to this.
They currently do not allow client-side access to their API. Their response to a similar question in comments:
We do not support accessing the API via client-side Javascript to
avoid the security issue of passing your API Key along to your users.

Cross-Origin Request Blocked: in javascript using XMLHttpRequest

I am trying to send a HTTP request in javascript using XMLHttpRequest and so I am using the following code in an HTML file. I have a server running which returns a dictionary of form {'test' : 'string'}.
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/test", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send();
xhr.onreadystatechange = processRequest;
console.log(xhr.status)
function processRequest(e)
{
if (xhr.readyState == 4)
{
alert(xhr.responseText);
}
}
</script>
However in spite of adding the header, I am getting a Cross-Origin Request Blocked: error in my console when I try to print xhr.status in the console it shows 0 as response.
I am using flask server which shows a bad message error on using HTTPS, so I am using an HTTP request.
You can not control CORS from front end. You have to put the CORS module to your back end server.
check the link flask cors.

Track 404 error pages or How to monitor http header request's status made by the browser using Javascript

I am developing a script that helps track 404 error pages (using JavaScript) at the client side. I searched for tutorials/ posts on the same but didn't find any helpful to me.
One post mentioned using curl (PHP) on the server side & redirect the user to a custom 404 page. But that doesn't address my problem (I want it at the client side).
This page mentions how to create an http object, open up a connection & detect its status in this way:
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
....
if( request.status == 404 )
print("404 error")
But over here we ourselves are making the http request & hence have access to the object. My aim is to detect any 404 page errors from the request send by the browser (due to user navigation).
Can we monitor the browser's http object for response statuses? How does Firebug's Network Analysis feature access the http headers? Can I replicate that in my script?
I have noticed that browser's Developer tool's Console gives a 404 error for missing pages as well as individual elements like images on that page.
These are the possible solutions I could imagine:
Monitor the response.status of every http request sent by the browser
Use Developer Tool's/Browser's Error Notification to track 404 errors using an "API" for extracting those error notifications of the tool (if it exists)
Thanks a lot
You mean something like this?
function returnStatus(req, status) {
//console.log(req);
if(status == 404) {
console.log("The url returned status code " + status);
}
else {
console.log("success");
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("http://yoururl.com");

Categories

Resources