Mastering Cross‑Origin Requests: From AJAX to JSONP and CORS
This tutorial explains the concept of cross‑origin requests, demonstrates practical AJAX calls between two Node.js servers on different ports, and walks through three major solutions—standard AJAX, JSONP, and CORS—while also covering alternative techniques like window.name and postMessage.
1. Cross‑Origin Request Definition
Browsers enforce the same‑origin policy, blocking client scripts from accessing resources on a different protocol, host, or port. Changing any of these three elements creates a cross‑origin request, which can be demonstrated by running two Node.js servers on ports 3000 and 3001.
2. Standard AJAX Call (Same Origin)
On server 3000 a page collects name and id values and sends them via $.ajax to http://localhost:3000/ajax/deal. The server appends the string " - server 3000 process" to each field and returns the JSON, which the browser logs.
$("#submit").click(function(){
var data = {
name: $("#name").val(),
id: $("#id").val()
};
$.ajax({
type: 'POST',
url: 'http://localhost:3000/ajax/deal',
data: data,
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data){ console.log(data.name); },
error: function(jqXHR,textStatus,errorThrown){ console.log('error '+textStatus+' '+errorThrown); }
});
});The same code works when the URL is changed to http://localhost:3001/ajax/deal, showing that the request reaches the server but the browser blocks the response because of the same‑origin restriction.
3. JSONP Implementation
JSONP bypasses the restriction by loading a <script> tag, which is not subject to the same‑origin policy. The server wraps the JSON in a callback function.
// client side JSONP request
$.ajax({
url: 'http://localhost:3001/ajax/deal',
data: data,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
cache: false,
timeout: 5000,
success: function(data){ console.log('ajax success callback: '+data.name); },
error: function(jqXHR,textStatus,errorThrown){ console.log('error '+textStatus+' '+errorThrown); }
});
// server side JSONP response
var callback = req.query.callback;
var jsonp = callback + '(' + JSON.stringify({name: req.body.name+' - server 3001 jsonp process', id: req.body.id+' - server 3001 jsonp process'}) + ');';
res.send(jsonp);Because JSONP uses only GET requests, it cannot send complex payloads and lacks robust error handling.
4. CORS Implementation
CORS (Cross‑Origin Resource Sharing) allows browsers to make normal XMLHttpRequest calls to other origins when the server includes specific response headers.
// client side CORS request (POST)
$.ajax({
type: 'POST',
url: 'http://localhost:3001/cors',
data: data,
dataType: 'json',
cache: false,
timeout: 5000,
success: function(data){ console.log(data.name); },
error: function(jqXHR,textStatus,errorThrown){ console.log('error '+textStatus+' '+errorThrown); }
});
// server side CORS headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.header('Content-Type', 'application/json;charset=utf-8');
var data = {
name: req.body.name + ' - server 3001 cors process',
id: req.body.id + ' - server 3001 cors process'
};
res.send(data);CORS supports all HTTP methods, provides proper error callbacks, and works in modern browsers.
5. Other Cross‑Domain Techniques
window.name : The window.name property persists across page loads within the same window, allowing data transfer between domains.
window.postMessage() : An HTML5 API that safely sends messages between windows or iframes from different origins.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
