Home > Web Front-end > JS Tutorial > body text

Introduction to solutions to cross-domain request POST

不言
Release: 2019-04-04 10:48:38
forward
3794 people have browsed it

This article brings you an introduction to the solution to cross-domain request POST. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Cross-domain request POST solution

Cookies generally cannot cross domains, and even POST requests generally cannot cross domains.
    //     请求代码示例
    $.ajax({
        url: url,
        type: "POST",
        data: metadata,
        dataType: 'json',
        xhrFields: {  
            withCredentials: true  
        },  
        crossDomain: true,
        success: function(){},
        error: function(){}
    });
Copy after login

1. By default, ajax (XMLHttpRequest() object and ie Microsoft.XMLHTTP object) is subject to the same origin policy and does not allow cross-domain requests. .

2. The cross domain of jsonp is to use the page to dynamically add script tags to reference cross domain resources to avoid this restriction, but there is no post method.

Solution: Server-side settings allow ajax requests to cross domains
    ##     服务端设置允许跨域代码,eg:
    header("Access-Control-Allow-Credentials: true");

    header("Access-Control-Allow-Origin: http://www.xxx.com");

    ## 设置成功后,在接口请求的Response Headers会看到一下以下允许跨越信息
    {
        Access-Control-Allow-Credentials:true
        Access-Control-Allow-Headers:x-requested-with,content-type
        Access-Control-Allow-Methods:POST
        Access-Control-Allow-Origin:http://www.aipai.com
    }
Copy after login

Cookies cross-domain solution

Ajax cross-domain request problem solved But when the backend needs to obtain cookies through the interface, there is also a cross-domain problem with cookies.

Cross-domain solution for cookies: Add the following parameters to the request, and the request header information will be Comes with cookie information
    // 代码
    $.ajax({
        ...
        xhrFields: {  
            withCredentials: true  
        },
        ...
    });
Copy after login

[Related recommendations: JavaScript video tutorial]

The above is the detailed content of Introduction to solutions to cross-domain request POST. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!