Table of Contents
Scenario recurrence process:
Home Backend Development PHP Tutorial javascript - Why can cookies under the second-level domain name be obtained, but cannot be sent back automatically using ajax, and cookies cannot be cross-domain?

javascript - Why can cookies under the second-level domain name be obtained, but cannot be sent back automatically using ajax, and cookies cannot be cross-domain?

Aug 18, 2016 am 09:16 AM
java javascript node.js php python

Scenario recurrence process:

<code>机器A局域网地址:192.168.9.8
机器B局域网地址:192.168.9.9
</code>
Copy after login
Copy after login
<code>分别配置机器A、B的hosts地址:

配置机器A的地址:192.168.9.8 --> a.site.com 
配置机器B的地址:192.168.9.9 --> b.site.com
</code>
Copy after login
Copy after login

Machine A is the front-end js code, starts the service, and requests the first address of machine B (representing the server side) on the browser http://b.site.com:8080/login/... , The server injects cookies at the same time as the request. Set the key of the cookie to 'site', the value to 'date', the doman to .site.com, and the path to /
. Then open a new page on the browser and make a request on the new page. http://a.site.com:8080/index, you can see the injected cookie through chrome console
http://b.site.com:8080/
, but... through ajax During the interface, the cookie did not appear in the request header. I tried various methods, including get, post, asynchronous, and synchronous, but none of them worked. Finally, the jsonp method was used, and the cookie appeared

The code that is not easy to use is as follows:
<code>$("a").click(function(event) {
        $.ajax({
            url: 'http://b.site.com:8080/test/test.htm',
            type: 'post',
            dataType: 'json',
            data: {'token': 'value'},
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
});
</code>
Copy after login
Copy after login

The useful code is as follows:

<code>function flightHandler(data) {
    console.log(data);
    // body...
};

$("a").click(function(event) {
    $.ajax({
         type: "get",
         url: "http://b.site.com:8080/test/test.htm",
         dataType: "jsonp",
         jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
         jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
         success: function(data){
            console.log(data);
         },
         error: function(){
             alert('fail');
         }
     });
});
</code>
Copy after login
Copy after login

Please ask the experts for help. If you can solve the problem, thank you very much

Reply content:

Scenario recurrence process:

<code>机器A局域网地址:192.168.9.8
机器B局域网地址:192.168.9.9
</code>
Copy after login
Copy after login
<code>分别配置机器A、B的hosts地址:

配置机器A的地址:192.168.9.8 --> a.site.com 
配置机器B的地址:192.168.9.9 --> b.site.com
</code>
Copy after login
Copy after login

Machine A is the front-end js code, starts the service, and requests the first address of machine B (representing the server side) on the browser http://b.site.com:8080/login/... , The server injects cookies at the same time as the request. Set the key of the cookie to 'site', the value to 'date', the doman to .site.com, and the path to /
. Then open a new page on the browser and make a request on the new page. http://a.site.com:8080/index, you can see the injected cookie through chrome console

http://b.site.com:8080/
, but... through ajax During the interface, the cookie did not appear in the request header. I tried various methods, including get, post, asynchronous, and synchronous, but none of them worked. Finally, the jsonp method was used, and the cookie appeared



The code that is not easy to use is as follows:

<code>$("a").click(function(event) {
        $.ajax({
            url: 'http://b.site.com:8080/test/test.htm',
            type: 'post',
            dataType: 'json',
            data: {'token': 'value'},
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
});
</code>
Copy after login
Copy after login
The useful code is as follows:
<code>function flightHandler(data) {
    console.log(data);
    // body...
};

$("a").click(function(event) {
    $.ajax({
         type: "get",
         url: "http://b.site.com:8080/test/test.htm",
         dataType: "jsonp",
         jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
         jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
         success: function(data){
            console.log(data);
         },
         error: function(){
             alert('fail');
         }
     });
});
</code>
Copy after login
Copy after login

Please ask the experts for help. If you can solve the problem, thank you very much

withCredentials=true, and ensure that the server allows cross-domain, please refer to cors

for details

A domain is not what you say it is. Cookie domain and ajax domain are not the same thing

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Apr 06, 2025 am 12:07 AM

The... (splat) operator in PHP is used to unpack function parameters and arrays, improving code simplicity and efficiency. 1) Function parameter unpacking: Pass the array element as a parameter to the function. 2) Array unpacking: Unpack an array into another array or as a function parameter.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

How to obtain real-time application and viewer data on the 58.com work page? How to obtain real-time application and viewer data on the 58.com work page? Apr 05, 2025 am 08:06 AM

How to obtain dynamic data of 58.com work page while crawling? When crawling a work page of 58.com using crawler tools, you may encounter this...

【Rust Self-study】Introduction 【Rust Self-study】Introduction Apr 04, 2025 am 08:03 AM

1.0.1 Preface This project (including code and comments) was recorded during my self-taught Rust. There may be inaccurate or unclear statements, please apologize. If you benefit from it, it's even better. 1.0.2 Why is RustRust reliable and efficient? Rust can replace C and C, with similar performance but higher security, and does not require frequent recompilation to check for errors like C and C. The main advantages include: memory security (preventing null pointers from dereferences, dangling pointers, and data contention). Thread-safe (make sure multi-threaded code is safe before execution). Avoid undefined behavior (e.g., array out of bounds, uninitialized variables, or access to freed memory). Rust provides modern language features such as generics

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

JavaScript code line break: How to handle long string and object attribute access gracefully? JavaScript code line break: How to handle long string and object attribute access gracefully? Apr 05, 2025 am 08:03 AM

Detailed explanation of JavaScript code line-breaking skills When writing JavaScript code, we often encounter a line of code that is too long, which not only affects the readability of the code...

See all articles