Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use CORS to solve Cross-domain problem in AJAX

Shulou Source: shulou.com Published: 2022-06-02 06:03:03 09月28日 Update

This article introduces how to use CORS to solve cross-domain problems in AJAX. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

What is AJAX?

AJAX is a way to get data from the server without refreshing the page, and the core object responsible for Ajax operation is the XMLHttpRequest (XHR) object.

The same origin policy is a major constraint on XHR, which sets the restriction of "same domain, same port, same protocol" for communication.

Attempts to access resources beyond the above restrictions will cause a security error unless an approved cross-domain solution is adopted.

This scheme is called CORS (Cross-Origin Resource Sharing) cross-source resource sharing.

Option 1:

/ / malpractice: browser compatibility problem

Server setting: Access-Control-Allow-Origin.

Remember: Access-Control-Allow-Origin cannot be set to *.

/ / set the available whitelist $white_list = ['http://t1.abc.com','http://t2.abc.com'];$_SERVER['HTTP_ORIGIN'] / / represents the domain name of the requesting party $http_origin =''; if (! empty ($_ SERVER ['HTTP_ORIGIN']) & & in_array ($_ SERVER [' HTTP_ORIGIN'], $white_list)) {$http_origin = $_ SERVER ['HTTP_ORIGIN'] / / set header information header ("Access-Control-Allow-Origin: {$http_origin}"); header ("Access-Control-Allow-Methods", "POST,GET"); header ('Access-Control-Allow-Credentials:true'); / / allow access to Cookie header (' Access-Control-Allow-Headers: XmuryRequestedWith`); / / set Headers} / / execute code logic.

Also: if the request is html, add the meta tag in the file.

Option 2:

/ / disadvantage: POST request is not supported.

There are a lot of online articles about using JSONP to solve cross-domain problems.

Option 3:

Similar to plan one.

Modify the Nginx Apache configuration.

/ / Nginxhttp {. Add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers XmurRequestedWhth; add_header Access-Control-Allow-Methods GET,POST,OPTIONS;} Apache:. Header set Access-Control-Allow-Origin * this is the end of sharing about how to use CORS to solve cross-domain problems in AJAX. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Solutions same content objects drawbacks articles more resources questions help services restrictions good security code information interests lists domain names guys Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information MySQL macOS Redmi Docker