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

Introduction to the complete structure of URL and same-origin cross-domain processing

不言
Release: 2019-03-02 15:15:51
forward
3509 people have browsed it

This article brings you an introduction to the complete structure of URL and same-origin cross-domain processing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Foreword: As working hours increase, the things I have learned before begin to be slowly forgotten. When I have time, I organize some information and keep it in order, which is also a kind of review.
I am just a front-end craftsman to prevent myself from becoming [a programmer who cannot work when the Internet is disconnected]

The complete structure of url

Protocol type (protocol)

The main types that can be specified through the URL are the following: http, ftp, gopher, telnet, file, etc.
URL composition protocol 1. protocol (protocol): Specify the transmission protocol used, listed in the following table A valid scheme name for the protocol attribute.
The most commonly used protocol is HTTP, which is also the most widely used protocol in the WWW.

http - Hypertext Transfer Protocol to access this resource. Format http://
https - Access the resource using Hypertext Transfer Protocol delivered by Secure Sockets Layer. Format https://
ftp - access resources through FTP. Format FTP://
mailto - email address accessed via SMTP. Format mailto:
ldap - Lightweight Directory Access Protocol search
file - The resource is a file on the local computer. Format file://
news —— Usenet news group
gopher —— Gopher protocol
telnet —— Telnet protocol

Hostname (hostname)
Refers to the Domain Name System (DNS) hostname or IP address of the server hosting the resource.
Sometimes, the username and password required to connect to the server can also be included before the host name (format: username:password).
Port number (port) Integer, optional, the default port of the scheme is used when omitted. Various transmission protocols have default port numbers,
For example, the default port of http is 80, and the default port of https is 443
Path and file name (path) A string separated by zero or more "/" symbols, generally used to represent a directory or file address on the host
Parameters (parameters) Passing parameters, there can be multiple Parameters are separated by the "&" symbol, and the name and value of each parameter are separated by the "=" symbol
Hash value # is used to guide the browser's actions and is completely useless to the server. Therefore, # is not included in the HTTP request.
None of these characters will be sent to the server.
Changing # does not trigger a page reload
Changing # will change the browser's access history

By default, Google's web spiders ignore the # part of the URL.
However, Google also stipulates that if you want the content generated by Ajax to be read by the browsing engine,
then you can use "#!" in the URL, and Google will automatically convert the content following it into the query string _escaped_fragment The value of _

Same origin policy

Same protocol, same domain name, same port, same port

If they are not from the same origin, there are three behaviors that are restricted

(1) Cookie、LocalStorage 和 IndexDB 无法读取。
(2) DOM 无法获得。
(3) AJAX 请求不能发送。
Copy after login

Cookie

Cookie is a small piece of information written by the server to the browser. Only web pages with the same origin can be shared.

Components of cookies
    Set-Cookie: NAME=VALUE;Expires=DATE;Path=PATH;Domain=DOMAIN_NAME;SECURE

    NAME=VALUE
    NAME是该Cookie的名称,VALUE是该Cookie的值。
    在字符串“NAME=VALUE”中,不含分号、逗号和空格等字符。
    
    Expires=DATE:Expires变量是一个只写变量,它确定了Cookie有效终止日期。
    该属性值DATE必须以特定的格式来书写:星期几,DD-MM-YY HH:MM:SS GMT,
    GMT表示这是格林尼治时间。
    反之,不以这样的格式来书写,系统将无法识别。
    该变量可省,如果缺省时,则Cookie的属性值不会保存在用户的硬盘中,
    而仅仅保存在内存当中,Cookie文件将随着浏览器的关闭而自动消失。
    
    Domain=DOMAIN-NAME:Domain该变量是一个只写变量,
    它确定了哪些Internet域中的Web服务器可读取浏览器所存取的Cookie,
    即只有来自这个域的页面才可以使用Cookie中的信息。
    这项设置是可选的,如果缺省时,设置Cookie的属性值为该Web服务器的域名。
    
    Path=PATH:Path属性定义了Web服务器上哪些路径下的页面可获取服务器设置的Cookie。
    一般如果用户输入的URL中的路径部分从第一个字符开始包含Path属性所定义的字符串,
    浏览器就认为通过检查。如果Path属性的值为“/”,
    则Web服务器上所有的WWW资源均可读取该Cookie。
    
    Secure:在Cookie中标记该变量,
    表明只有当浏览器和Web Server之间的通信协议为加密认证协议时,
    浏览器才向服务器提交相应的Cookie。当前这种协议只有一种,即为HTTPS。
Copy after login
The transmission format of cookies in Request Headers
    Cookie: KEY=VALUE; KEY=VALUE; KEY=VALUE
    是没有 域 和 过期时间 的
Copy after login

Cross-domain processing

The first-level domain names of the two web pages are the same, but Different second-level domain names, browsers allow sharing cookies by setting document.domain.

document.domain = 'example.com';
Copy after login

If the two web pages have different sources, they cannot get the other party's DOM.

典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。
Copy after login

AJAX

In addition to setting up a server proxy (the browser requests the same origin server, and then the latter requests external services),

Cross-domain processing of the development environment in the vue project

proxyTable

dev: {
     
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    proxyTable: {
        '/api': {
            target: 'http://temp.com',// 请换成你需要跨域请求的地址
            changeOrigin: true,
            pathRewrite: {
              '^/api': ''
            }
        }
    }
}
Copy after login

The /api of pathRewrite in proxyTable is understood to use '/api' instead of the address in the target.
When we drop the interface in the subsequent component Directly use api instead

There are three ways to circumvent this restriction

JSONP
WebSocket
CORS
Copy after login
    JSONP
    是服务器与客户端跨源通信的常用方法。
    最大特点就是简单适用,老式浏览器全部支持,服务器改造非常小。
    它的基本思想是,网页通过添加一个<script>元素,向服务器请求JSON数据,
    这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来。
    
    WebSocket
    WebSocket是一种通信协议,使用ws://(非加密)和wss://(加密)作为协议前缀。
    该协议不实行同源政策,只要服务器支持,就可以通过它进行跨源通信。

    CORS
    CORS是跨源资源分享(Cross-Origin Resource Sharing)的缩写。
    它是W3C标准,是跨源AJAX请求的根本解决方法。
    相比JSONP只能发GET请求,CORS允许任何类型的请求。
Copy after login

CORS detailed explanation

CORS needs to be supported by both the browser and the server. Currently, all browsers support this function, and IE browser cannot be lower than IE10.

The entire CORS communication process is automatically completed by the browser and does not require user participation. For developers, there is no difference between CORS communication and AJAX communication from the same source, and the code is exactly the same. Once the browser discovers that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes an additional request will be made, but the user will not feel it.

Therefore, the key to achieving CORS communication is the server. As long as the server implements the CORS interface, cross-origin communication is possible.

Two kinds of requests

Browsers divide CORS requests into two categories: simple requests (simple requests) and non-so-simple requests (not-so-simple requests).

As long as the following two conditions are met at the same time, it is a simple request

(1)请求方法是以下三种方法之一:
    HEAD
    GET
    POST
    
(2)HTTP的头信息不超出以下几种字段:
    Accept
    Accept-Language
    Content-Language
    Last-Event-ID
    Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain
    
凡是不同时满足上面两个条件,就属于非简单请求。
Copy after login
简单请求

对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个Origin字段。

下面是一个例子,浏览器发现这次跨源AJAX请求是简单请求,就自动在头信息之中,添加一个Origin字段。

    
    GET /cors HTTP/1.1
    Origin: http://api.bob.com
    Host: api.alice.com
    Accept-Language: en-US
    Connection: keep-alive
    User-Agent: Mozilla/5.0...
Copy after login

上面的头信息中,Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。服务器根据这个值,决定是否同意这次请求。

如果Origin指定的源,不在许可范围内,服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含Access-Control-Allow-Origin字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequest的onerror回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。

如果Origin指定的域名在许可范围内,服务器返回的响应,会多出几个头信息字段。

    
    
    Access-Control-Allow-Origin: http://api.bob.com
    Access-Control-Allow-Credentials: true
    Access-Control-Expose-Headers: FooBar
    Content-Type: text/html; charset=utf-8
Copy after login

上面的头信息之中,有三个与CORS请求相关的字段,都以Access-Control-开头。

  1. Access-Control-Allow-Origin

    该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求

  2. Access-Control-Allow-Credentials

    该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。

  3. Access-Control-Expose-Headers

    该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader('FooBar')可以返回FooBar字段的值。

非简单请求

非简单请求是那种对服务器有特殊要求的请求,比如请求方法是PUT或DELETE,或者Content-Type字段的类型是application/json。

非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)。

浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。

"预检"请求用的请求方法是OPTIONS,表示这个请求是用来询问的。头信息里面,关键字段是Origin,表示请求来自哪个源。

除了Origin字段,"预检"请求的头信息包括两个特殊字段。

Access-Control-Request-Method

该字段是必须的,用来列出浏览器的CORS请求会用到哪些HTTP方法,上例是PUT。

Access-Control-Request-Headers

该字段是一个逗号分隔的字符串,指定浏览器CORS请求会额外发送的头信息字段,上例是X-Custom-Header。

OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
Copy after login

预检请求的回应

服务器收到"预检"请求以后,检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后,确认允许跨源请求,就可以做出回应。

    HTTP/1.1 200 OK
    Date: Mon, 01 Dec 2008 01:15:39 GMT
    Server: Apache/2.0.61 (Unix)
    Access-Control-Allow-Origin: http://api.bob.com
    Access-Control-Allow-Methods: GET, POST, PUT
    Access-Control-Allow-Headers: X-Custom-Header
    Content-Type: text/html; charset=utf-8
    Content-Encoding: gzip
    Content-Length: 0
    Keep-Alive: timeout=2, max=100
    Connection: Keep-Alive
    Content-Type: text/plain
    
    
上面的HTTP回应中,关键的是Access-Control-Allow-Origin字段,
表示http://api.bob.com可以请求数据。该字段也可以设为星号,表示同意任意跨源请求。
Copy after login

The above is the detailed content of Introduction to the complete structure of URL and same-origin cross-domain processing. 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 admin@php.cn
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!