Home Web Front-end JS Tutorial Set Access-Control-Allow-Origin to achieve cross-domain access

Set Access-Control-Allow-Origin to achieve cross-domain access

May 22, 2018 pm 05:28 PM
accomplish access

This article mainly introduces Ajax setting Access-Control-Allow-Origin to achieve cross-domain access. It is very good and has reference value. Friends in need can refer to it

ajax cross-domain access is an old There are many solutions to the problem. The more commonly used method is the JSONP method. The JSONP method is an unofficial method, and this method only supports the GET method, which is not as safe as the POST method.

Even if you use the jsonp method of jQuery and set the type to POST, it will automatically change to GET.

Official problem description:

“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_= [TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.

If you use POST across domains, You can create a hidden iframe to achieve this, which is the same as ajax uploading images, but this will be more troublesome.

Therefore, it is relatively simple to achieve cross-domain access by setting Access-Control-Allow-Origin.

For example: the client's domain name is www.client.com, and the requested domain name is www.server.com

If you directly use ajax to access, there will be the following error

XMLHttpRequest cannot load http://www.server.com/server.PHP. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.

Add

// 指定允许其他域名访问 
header('Access-Control-Allow-Origin:*'); 
// 响应类型 
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置 
header('Access-Control-Allow-Headers:x-requested-with,content-type');
Copy after login

to the requested Response header to achieve ajax POST cross-domain access.

The code is as follows:

client.html Path: http://www.client.com/client.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
 <head> 
 <meta http-equiv="content-type" content="text/html;charset=utf-8"> 
 <title> 跨域测试 </title> 
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 
 </head> 
 <body> 
 <p id="show"></p> 
 <script type="text/javascript"> 
 $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}) 
 .done(function(data){ 
 document.getElementById("show").innerHTML = data.name + &#39; &#39; + data.gender; 
 }); 
 </script> 
 </body> 
</html>
Copy after login

server.php Path: http://www .server.com/server.php

<?php 
$ret = array( 
 &#39;name&#39; => isset($_POST[&#39;name&#39;])? $_POST[&#39;name&#39;] : &#39;&#39;, 
 &#39;gender&#39; => isset($_POST[&#39;gender&#39;])? $_POST[&#39;gender&#39;] : &#39;&#39; 
); 
header(&#39;content-type:application:json;charset=utf8&#39;); 
header(&#39;Access-Control-Allow-Origin:*&#39;); 
header(&#39;Access-Control-Allow-Methods:POST&#39;); 
header(&#39;Access-Control-Allow-Headers:x-requested-with,content-type&#39;); 
echo json_encode($ret); 
?>
Copy after login

Access-Control-Allow-Origin:* means allowing cross-domain access from any domain name

If you needSpecify a domain name to allow it For cross-domain access, just change Access-Control-Allow-Origin:* to Access-Control-Allow-Origin:allowed domain names

For example: header('Access-Control- Allow-Origin:http://www.client.com');

If you needSet multiple domain namesto allow access, you need to use php to process it

For example Allow www.client.com and www.client2.com to have cross-domain access to

server.php and change it to

<?php 
$ret = array( 
 &#39;name&#39; => isset($_POST[&#39;name&#39;])? $_POST[&#39;name&#39;] : &#39;&#39;, 
 &#39;gender&#39; => isset($_POST[&#39;gender&#39;])? $_POST[&#39;gender&#39;] : &#39;&#39; 
); 
header(&#39;content-type:application:json;charset=utf8&#39;); 
$origin = isset($_SERVER[&#39;HTTP_ORIGIN&#39;])? $_SERVER[&#39;HTTP_ORIGIN&#39;] : &#39;&#39;; 
$allow_origin = array( 
 &#39;http://www.client.com&#39;, 
 &#39;http://www.client2.com&#39; 
); 
if(in_array($origin, $allow_origin)){ 
 header(&#39;Access-Control-Allow-Origin:&#39;.$origin); 
 header(&#39;Access-Control-Allow-Methods:POST&#39;); 
 header(&#39;Access-Control-Allow-Headers:x-requested-with,content-type&#39;); 
} 
echo json_encode($ret); 
?>
Copy after login

. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax implements dynamic loading of data

Solution to spring mvc returning json data toajaxerror reporting parseerror problem

Various postures of front-endajax to interact with the back-end (graphic tutorial)

The above is the detailed content of Set Access-Control-Allow-Origin to achieve cross-domain access. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Use Java to write code to implement love animation Use Java to write code to implement love animation Dec 23, 2023 pm 12:09 PM

Realizing love animation effects through Java code In the field of programming, animation effects are very common and popular. Various animation effects can be achieved through Java code, one of which is the heart animation effect. This article will introduce how to use Java code to achieve this effect and give specific code examples. The key to realizing the heart animation effect is to draw the heart-shaped pattern and achieve the animation effect by changing the position and color of the heart shape. Here is the code for a simple example: importjavax.swing.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

How to solve the problem of inaccessibility after Tomcat deploys war package How to solve the problem of inaccessibility after Tomcat deploys war package Jan 13, 2024 pm 12:07 PM

How to solve the problem that Tomcat cannot successfully access the war package after deploying it requires specific code examples. As a widely used Java Web server, Tomcat allows developers to package their own developed Web applications into war files for deployment. However, sometimes we may encounter the problem of being unable to successfully access the war package after deploying it. This may be caused by incorrect configuration or other reasons. In this article, we'll provide some concrete code examples that address this dilemma. 1. Check Tomcat service

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles