How to Solve Cross-Origin Issues with CORS Instead of JSONP

This article explains why JSONP is limited to GET requests, demonstrates a Baidu API call that works via CORS, and shows how to enable CORS on the server with the Access-Control-Allow-Origin header for all or specific origins.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Solve Cross-Origin Issues with CORS Instead of JSONP

Cross‑origin requests are a common problem in frontend development, and many developers resort to JSONP.

JSONP is easy to use—once the frontend and backend agree on a callback function name, data can be fetched—but it only works with GET requests and is inconvenient for public APIs.

For example, calling Baidu’s weather API with jQuery:

var api = 'http://apis.baidu.com/heweather/weather/free?city=beijing';
$.get(api, function (data) {
    alert(data);
});

This request succeeds without any special handling because the server already supports CORS.

The solution is to enable CORS (Cross‑Origin Resource Sharing) on the server by adding the Access-Control-Allow-Origin response header.

To allow any origin: Access-Control-Allow-Origin: * To restrict to a specific domain: Access-Control-Allow-Origin: http://www.a.com In PHP you can set it with: header('Access-Control-Allow-Origin: *'); Note: CORS is widely supported by modern browsers, and even IE8 has partial support, but you should test thoroughly for compatibility.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendCORSCross-OriginWeb SecurityJSONP
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.