Can I search Google with XMLHttpRequest()?

老子叫甜甜 提交于 2019-12-08 06:24:06

问题


Can I search Google with a cross-origin XMHhttpRequest()?

var xhr = XMLHttpRequest();
xhr.open("GET", www.google.com/?q=what+you+want+to+search, true);

回答1:


Try it:

curl -H "Origin: http://domain.com" -X OPTIONS --head https://www.google.com/

This currently gives you:

HTTP/1.1 405 Method Not Allowed
Content-Type: text/html; charset=UTF-8
Content-Length: 962
Date: Fri, 21 Jun 2013 17:58:45 GMT
Server: GFE/2.0

So no, you can't, at least not with their public facing website. There would be an Access-Control-Allow-Origin: * in there if that was the case, with a 200 OK. The * is a wildcard for "any domain". So it would either have to be this, or it would have to match your origin.

Even if it did return the correct header, you have to have CORS support in the browser. You can see browser compatibility here. IE 8 and 9 only supports CORS through XDomainRequest, which has heavy restrictions (no cookies, or custom headers, for example). You can read more about access control headers here.

When CORS fails, same origin policy is used.

There is a way though. The Google REST API does support cross origin requests:

curl -H "Origin: http://domain.com" -X GET --head "https://www.googleapis.com/customsearch/v1?"

Which gives you:

HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: http://domain.com
Content-Type: application/json; charset=UTF-8
Access-Control-Expose-Headers: Content-Encoding,Content-Length,Content-Type,Server
Date: Fri, 21 Jun 2013 18:12:51 GMT
Expires: Fri, 21 Jun 2013 18:12:51 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Transfer-Encoding: chunked

Notice the Access-Control-Allow-Origin: http://domain.com.

So assuming you have an API key, you can, if you use the API.



来源:https://stackoverflow.com/questions/17241189/can-i-search-google-with-xmlhttprequest

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