AJAX and Cross-Site Scripting to Read the Header

我的梦境 提交于 2019-12-12 16:38:00

问题


Help me understand AJAX and cross-site scripting a little better. Writing AJAX is fairly straight forward. If I want to asynchronously read HTTP header of a website, I'd do something like this:

var req = new XMLHttpRequest();
req.open('HEAD', 'http://www.stackoverflow.com/', true);
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      alert(req.responseText);
     else
      alert("Error loading page");
  }
};
req.send(null);

However, when I copy and paste this into a simple HTML page using notepad and try to run it locally, the request status doesn't seem to return 200. I am assuming this is due to cross-site scripting. How would I get around this?


回答1:


You are right in that making requests across domains is not allowed unless you are using Cross-Origin Resource Sharing (CORS, http://www.w3.org/TR/cors/). CORS has a client-side and server side component. On the client side, the request looks mostly like a regular XmlHttpRequest, except you have a few other properties and handlers you can configure. On the server, the response will need to emit some special http headers. This article gives a good breakdown of how CORS works on the client and server: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/




回答2:


My first guess would be to try and make a local PHP file which acts like a gateway:

<?php
  echo get_headers($_GET['url']);
?>

Then, perform a GET request with the url of your target site as the parameter, and parse the .responseText of that request to determine the response header of your original.

I don't think it's possible with pure JS, so you'll have to use some serverside code.




回答3:


There are two types of "locally":

  • Using a local server (http://localhost/)
  • Accessing HTML file directly (file:///C:\a\b\c.html)

AJAX won't work, ever, in the second case.




回答4:


You can't make an ajax request to http://stackoverflow.com if your page is being served on http://localhost/...

http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests



来源:https://stackoverflow.com/questions/5533207/ajax-and-cross-site-scripting-to-read-the-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!