JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls

The XMLHttpRequest object (also known as the XMLHTTP object in Internet Explorer) is at the core of today‘s most exciting AJAX web applications. But actually writing client web applications that use this object can be tricky given restrictions imposed by web browsers on network connections across domains. This HOWTO provides describes the issue in simple, easy to understand language and provides one possible solution: a web proxy that relays network requests from your web server to services such as the Yahoo! Web Service APIs.

Why You Need a Proxy

All modern web browsers impose a security restriction on network connections, which includes calls to XMLHttpRequest. This restriction prevents a script or application from making a connection to any web server other than the one the web page originally came from (Internet Explorer will allow cross-domain requests if the option has been enabled in the preferences). If both your web application and the XML data that application uses come directly from the same server, then you do not run into this restriction.

If, however, you serve your web application from one web server and you make web service data requests to another server -- for example, to the Yahoo! Web Services -- then the browser prevents the connection from being opened at all. Bummer.

There are a number of solutions to this problem but the most commonly-used one is to install a proxy on your web server. Instead of making your XMLHttpRequest calls directly to the web service, you make your calls to your web server proxy. The proxy then passes the call onto the web service and in return passes the data back to your client application. Because the connection is made to your server, and the data comes back from your server, the browser has nothing to complain about.

For security reasons it‘s a good idea for any proxy you install on your web server should be limited in use. An open proxy that passes on connections to any web site URL is open to abuse. Although it is difficult to limit the connections to your proxy from only your application, you can prevent the proxy from making connections to servers other than those you specify. Hard code the URL to connect to in the proxy itself or provide limited options. This makes the proxy less open and less useful to users other than your client application.

PHP Proxy for Yahoo! Web Services

For the Yahoo! Developer Network JavaScript Developer Center we have provided sample code for a simple web proxy, written in PHP, that takes requests for the Yahoo! Search APIs. You can install this proxy on your own web server in any convenient location (your web server must be set up to run PHP).

The proxy encodes the Yahoo! Web services site URL in a global variable called HOSTNAME. ou will need to modify this variable to refer to the Yahoo! Web Services API you‘ll be using. This is the domain used by the Yahoo! Search web services; other domains include Yahoo! Local (http://local.yahooapis.com) and Yahoo! Travel (http://api.travel.yahoo.com).

define (‘HOSTNAME‘, ‘http://search.yahooapis.com/‘);

To use the PHP web proxy in your client application, the URL for the request in the JavaScript code includes the path for the Yahoo! Web Services request, minus the domain name. The domain name is added by the proxy itself on the server side. This code snippet comes from a more complete XMLHttpRequest code sampleon our JavaScript Developer Center.

// The web services request minus the domain name
var path = ‘VideoSearchService/V1/videoSearch?appid=YahooDemo&query=madonna&results=2‘;

// The full path to the PHP proxy
var url = ‘http://localhost/php_proxy_simple.php?yws_path=‘ + encodeURIComponent(path);
... // core xmlhttp code
xmlhttp.open(‘GET‘, url, true);

Note that although this example uses an HTTP GET request, the sample PHP web proxy also supports POST.

You could modify the proxy to do post-processing of the data you get from the request on the server side, for example, to strip out only the elements you‘re interested in or the parse the XML into a format you can more comfortably handle in JavaScript.

Other Solutions

In addition to using a web proxy to pass web services data to your application, there are several other options to working around cross-domain browser restrictions:

  • Use apache‘s mod_rewrite or mod_proxy to pass requests from your server to some other server. In your client code you just make the request as if it was actually on your server -- no browser problems with that. Apache then does its magic and makes the request to the other server for you.
  • Use JSON and dynamic <script> tags instead of XML and XMLHttpRequest. You can get around the browser security problem altogether by making your web services request directly inside a <script> tag. If the Yahoo! Web Service you‘re using can output JSON (using the output=json and callback=function parameters), the data you get back from the web service is evaluated as a JavaScript object when the page is loaded. See our JSON Documentation for an example of how to do this in your own scripts.
  • Digitally sign your scripts. In Firefox you can apply a digital signature to your script and those scripts will then be considered "trusted" by the browser. Firefox will then let you make XMLHttpRequests to any domain. However, no other browsers support script signing at this time, so this solution is of limited use.

For More Information

For more information on JavaScript, XMLHttpRequest, Yahoo! Web Services APIs and other JavaScript development topics, see The Yahoo! Developer Network JavaScript Developer Center.

From: yahoo developer network

时间: 2024-08-04 08:41:15

JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls的相关文章

[cross domain] four approachs to cross domain in javascript

four approachs can cross domain in javascript 1.jsonp 2.document.domain(only in frame and they have one same parent domain) 3.window.name 4.window.postMessage(only in Html5) original website:http://www.cnblogs.com/2050/p/3191744.html

javascript使用web proxy来实现ajax cross-domain通信

在现代浏览器中,都强加了对javacript代码的访问限制,比如一个页面的js无法向非同源的url实现ajax请求,获得数据.在这时,是浏览器端会报错: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status co

前端开发各种cross之cross domain

作为一个苦逼前端开发工程师,不得不面对各种cross,比如面对五花八门的浏览器我们必须cross browser,面对各种终端,我们必须cross device,在这么多年的前端开发经历中,在不同的域之间穿越中,遭受各种折磨,所以这次和大家分享的是cross domain. 这次分享的cross domain,是包括所有跨域调用,无论是跨域获取数据,还是跨域跨frame调用,所以会分为两部分,这次会先分享跨域获取数据,跨域获取数据大概有以下方式. 1.jsonp方式这是最简单,也是最实用的跨域获

构建基于Javascript的移动web CMS——Hello,World

在一篇构建基于Javascript的移动web CMS入门--简介中简单的介绍了关于墨颀CMS的一些原理,其极框架组成,于是开始接着应该说明一下这个CMS是如何一步步搭建起来. RequireJS 使用 库及依赖 这里用的是bower的JS来下载库,详细可以参考一下bower install js使用bower管理js 这篇文章. 需要下载的库有 RequireJS Backbone Underscore Mustache jQuery 使用RequireJS 引用官网的示例 <!DOCTYPE

JAVASCRIPT实现的WEB页面跳转以及页面间传值方法

在WEB页面中,我们实现页面跳转的方法通常是用LINK,BUTTON LINK ,IMG LINK等等,由用户点击某处,然后直接由浏览器帮我们跳转. 但有时候,需要当某事件触发时,我们先做一些操作,然后再跳转,这时,就要用JAVASCRIPT来实现这一跳转功能. 下面是具体的做法: 一:跳转到新页面,并且是在新窗口中打开时: 复制代码 代码如下: function gogogo() { //do someghing here... window.open("test2.html");

每天一个JavaScript实例-确定web页面的区域

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>每天一个JavaScript实例-确定web页面的区域</title> <script> function size(){ var width = 0; var heigh

构建基于Javascript的移动web CMS——加载JSON文件

在上一篇中说到了如何创建一个Django Tastypie API给移动CMS用,接着我们似乎也应该有一个本地的配置文件用于一些简单的配置,如"获取API的URL"."产品列表"."SEO"(在一开始的时候发现这是不好的,后面又发现Google的爬虫可以运行Javascript,不过也是不推荐的.)这些东西是不太需要修改的,直接写在代码中似乎又不好,于是放到了一个叫作configure.json的文件里. RequireJS Plugins 网上

遇到 Error creating the Web Proxy specified in the &#39;system.net/defaultProxy&#39; configuration section的解决办法

用记事本编辑*.EXE.config,在“<system.net>”节点加入<defaultProxy> <proxy usesystemdefault="False" /> </defaultProxy> 完整的: <?xml version="1.0"?> <configuration> <system.net> <settings> <httpWebReque

JavaScript &amp; jQuery交互式Web前端开发

这篇是计算机中网络编程javascript类的优质预售推荐<JavaScript & jQuery交互式Web前端开发>. 内容简介 欢迎选择一种更高效的学习JavaScript和jQuery的方式. 你是一名JavaScript新手?或是您曾经向自己的Web页面上添加过一些脚本,但想以一种更好的方式来实现它们?本书非常适合您.本书不仅向您展示如何阅读和编写JavaScript代码,同时还会以一种简单且视觉化的方式,教您有关计算机编程的基础知识.阅读本书之前,您只需要对HTML和CSS