Interview Questions Cross-Domain

https://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html
https://juejin.cn/post/6844903972742889480#heading-10

Homology Policy

concept
Homology Policy: Same Port, Same Domain Name, Same Protocol

Choice Question: Is the following homology policy in line with
http://www.example.com/dir2/other.html: Homology
http://example.com/dir/other.html: different sources (different domain names)
http://v2.www.example.com/dir/other.html: different sources (different domain names)
http://www.example.com:81/dir/other.html: different sources (different ports)

objective
The purpose of homology policy is to ensure the security of user information and prevent malicious websites from stealing data.
Imagine a situation where Web site A is a bank and users log in and browse other websites.What happens if other websites can read Cookie s from website A?

Clearly, if a Cookie contains privacy, such as the total amount of deposits, this information can be leaked.Even more scary is that cookies are often used to save users'login status, and if users do not sign out, other websites can impersonate users and do whatever they want.Because browsers also stipulate that submitting forms is not restricted by homology policies.

Thus, a "homology policy" is necessary, otherwise cookies can be shared and the Internet will be unsecured.

Both localhost and 127.0.0.1 point to the local machine, but they are also cross-domain.

Limited range
"Homology policy" is becoming more stringent.Currently, three types of behavior are restricted if they are not homologous

(1) Cookie,LocalStorage and IndexDB Unable to read.

(2) DOM Not available.

(3) AJAX The request could not be sent.

There is no cross-domain situation (regardless of homology policy)

Server side requests server side does not exist cross domain (browser requests server has homology policy)
< img src="Cross-domain picture address"> (<img>Labeled src Attribute does not exist across domains)
<link href="Cross-domain css address"> (<link>Labeled href Attribute does not exist across domains)
<script src="Cross-domain js address"></script> (<script>Labeled src Attribute does not exist across domains)

Common methods across domains

  • JSONP
  • WebSocket
  • CORS

JSONP

JSONP is a common method of cross-source communication between servers and clients.The biggest feature is simple and applicable, all supported by old browsers, and very small server transformation.

The basic idea is that web pages request JSON data from the server by adding a <script>element, which is not restricted by homology policies;When the server receives the request, it returns the data in a callback function with the specified name.

First, the page dynamically inserts the <script>element, which makes requests to cross-source web addresses.

function addScriptTag(src) {
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.src = src;
  document.body.appendChild(script);
}

window.onload = function () {
  addScriptTag('http://example.com/ip?callback=foo');
}

function foo(data) {
  console.log('Your public IP address is: ' + data.ip);
};

The above code makes a request to server example.com by dynamically adding the <script>element.Note that the request's query string has a callback parameter that specifies the name of the callback function, which is required for JSONP.

JSONP(get form)

Q: Why does jsonp only support get requests?

JSONP Is a [request a paragraph] JS A script that treats the results of executing this script as data).

So you can POST A passage script Do labels introduce scripts?

(If you've seen it JSONP The source code of the library knows that the common implementation code is document.createElement('script') Generate a script Label, then insert body Just inside.There is no room to format the request at all here).

therefore JSONP The principle of implementation is to create a script Label, Request more api Address to src in. This request can only be used GET Method, Not possible POST

Principle:
By exploiting the bug that the <script>tag has no cross-domain restrictions, web pages can get JSON data generated dynamically from other sources.JSONP requests must require the other party's server to support them
Advantages and disadvantages

1.Advantage
1.1 It's not like XMLHttpRequest Object Implemented Ajax The request is then restricted by the same origin policy, JSONP Homology policies can be crossed;
1.2 It's more compatible and works in older browsers without requiring XMLHttpRequest or ActiveX Support
1.3 After the request is complete, it can be invoked by calling callback Method to return the result.The callback method is given permission to the caller.This is in place
 When controller Layers and view The layers finally split.I provided jsonp Services only provide service-only data, as far as providing services to
 After page rendering and follow-up view It is good that the operation is defined by the caller himself.If two pages need to render the same data,
All you need is a different rendering logic, which can all use the same one jsonp Service.
2.shortcoming
2.1 It only supports GET Request without support POST And other types HTTP request
2.2 It only supports cross-domain HTTP Requesting this does not resolve how two pages from different domains work JavaScript Call problem.
2.3 jsonp When a call fails, it does not return a variety of HTTP Status code.
2.4 The disadvantage is security.In case provided jsonp There is a page injection vulnerability in the service that it returns javascript Content is controlled
 Of.So what's the result?All calls to this jsonp All websites have bugs.So you can't control the danger under a domain name...
So in use jsonp You have to make sure you use jsonp The service must be secure and trusted.

WebSocket

WebSocket is a communication protocol that uses ws://(unencrypted) and wss://(encrypted) as protocol prefixes.The protocol does not implement a homology policy and can be used for cross-source communication as long as the server supports it.

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

In the code above, one field is Origin, which indicates the origin of the request, which domain name it originated from.

It is because of the Origin field that WebSocket does not implement a homology policy.This is because the server can use this field to determine whether to allow this communication.

CORS

Q: Comparison of CORS and JSONP

CORS and JSONP Use for the same purpose, but compare JSONP More powerful.

JSONP Only supported GET Request, CORS Supports all types of HTTP Request. JSONP Advantages include support for older browsers and the ability to support CORS Web site requests data.

Q: What is CORS?

The full name of CORS is Cross-origin resource sharing.It allows browsers to issue XMLHttpRequest requests to cross-source servers, overcoming the limitation that AJAX can only be used from the same source.
Q: How do you understand CORS?

If wang.com and ergou.com Both websites are mine, I just want to wang.com To visit ergou.com What about the data inside?
It only needs wang.com Write in response header ergou.com Accessible.This is it. CORS. 
Realization CORS The key to communication is the server.As long as the server implements CORS Interfaces allow you to communicate across sources.

Q: Problems with CORS

I won't support it IE8/9,If you want to IE8/9 Use CORS Cross-domain Requirements XDomainRequest Object to support CORS. 

Simple request
A simple request is one that meets the following criteria:

Request method is HEAD, POST or GET
http header information does not exceed the following fields: Accept, Accept-Language, Content-Language, Last-Event-ID, Content-Type (limited to three values: application/x-www-form-urlencoded, multipart/form-data, text/plain)

The implementation of a simple request is to add an Origin field to the information header:

GET /cors HTTP/1.1
Origin: http://wang.com
Host: api.ergou.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0
...

Origin is used to indicate from which source the request originated and the server will use Origin values to determine whether or not the request was accepted.
If the source represented by Origin is not accepted by the server, that is, if the browser finds that there is no Access-Control-Allow-Origin field in the header of the response, an error will be thrown automatically.
Note: This error is not recognized by the status code, which is also a disadvantage of cross-domain requests through CORS.

Choice question

1. For cross-domain solutions, the following is true
A,Can be utilized flash Of http Request to handle cross-domain issues
B,adopt iframe Set up document.domain Achieving cross-domain
C,Normally, m.toutiao.com Yes? ajax request www.toutiao.com Interface under domain name and get response
D,adopt jsonp Method can be issued post Request interfaces under other domain names

Correct answer: B

Resolution:

B,Inside Station AJAX Cross-domain can pass through document.domain and iframe Realization, document.domain;This is used for cross-domain access where the primary domain name is the same and the subdomain name is different
C,Homology Policy
D,JSONP The disadvantage is that it only supports GET Request without support POST And other types HTTP Request;It only supports cross-domain
HTTP Requesting this does not resolve how two pages from different domains work JavaScript Call problem.
2. For cross-domain solutions, the following is true
A,If the interface is post Request, back-end personnel will interface method Change to get Can be solved
B,jsonp Inside is ajax Realized
C,Recommended for online use webpack devServer proxy Solve
D,Recommend online interface modifications Nginx increase header Head Solution

Correct answer: C

B,jsonp Request; jsonp The principle is to use<script>The cross-domain nature of tags allows you to load resources from other domains without restrictions, similar to tags<img>.
JSONP Core Principles script Labels are not affected by homology policy.Dynamic insertion into DOM In script The script can be executed immediately.and ajax That's OK.
D,nginx For reverse proxying, the response header is set to the back end

Tags: Front-end Interview

Posted on Fri, 03 Sep 2021 02:10:03 -0400 by wolfrock