Hello everyone, I’m Daotin, captain of the front end, want to get more exciting content of the front end, follow me, unlock the new position of the front end growth.

Recent updates:

  • JS static type detection, has an internal flavor
  • Lazy image loading in 3 minutes
  • Talk about Web Notification in HTML5

The following text:

preface

Automatic access to the front end, the word cross-domain has been ringing in the ears. Since this aspect has been dealt with in most of the projects I took over, and I have always felt ambiguous about this aspect, so I will take some time to sort it out today.

Why cross-domain

The idea of cross-domain comes from something called the same origin policy. The same origin policy is a very important security mechanism that is implemented for security purposes on the browser (note that the browser is independent of the communication protocol).

By default, Ajax can only retrieve data from the same source, and cannot retrieve data from non-same source.

What is homology?

  • The agreement is the same
  • Domain name is the same
  • The same port

For example, http://www.example.com/dir/page.html, the agreement is http://, a domain name is www.example.com, port is 80 (the default port can be omitted). What happens if the site accesses data on the server below?

URL The results of why
https://www.example.com/dir/other.html Different source Protocol is different, HTTPS and HTTP
http://en.example.com/dir/other.html Different source Domain name is different
http://www.example.com:81/dir/other.html Different source Different ports
http://www.example.com/dir/page2.html homologous Same protocol, same domain name, same port
http://www.example.com/dir2/page.html homologous Same protocol, same domain name, same port

Then. To retrieve data from non-same source addresses, use cross-domain. Whether it’s Ajax or cross-domain, it’s all about accessing the server’s data. In simple terms, Ajax is for accessing data from your own server, and cross-domain is for accessing data from other servers (such as weather information, flight information, etc.).

Purpose of the same-origin policy

In order to ensure the security of user information, prevent malicious websites from stealing data.

“Imagine A situation where site A is A bank, and the user logs in, and then goes to another site. What happens if other sites can read site A’s cookies?

Obviously, if the Cookie contains privacy (such as the total amount of deposits), this information can be leaked. What’s more, cookies are often used to save a user’s login status. If the user does not log out, other websites can impersonate the user and do whatever they want. The browser also states that submitting forms is not subject to the same origin policy.

Therefore, the same origin policy is necessary, otherwise cookies can be shared, the Internet is not safe.”

Via @ ruan

Implement a cross-domain approach

  • The reverse proxy
  • JSONP
  • WebSocket
  • CORS (Radical Solution)

The reverse proxy

A reverse proxy uses its own server to request data from the target server on the back end and then return it to the client. It’s like being a middleman.

The most commonly used reverse proxy server is Nginx. But node.js, implemented as front-end code, can also set up reverse proxy servers.

Here’s a brief introduction to reverse proxy using Node services.

For this to happen, the front-end development environment must be running on nodeJS services. Fortunately, the front-end development automation tools are built on NodeJS, so this premise is not very important.

Such as I have a backend interface: http://39.105.136.190:3000/zhuiszhu/goods/getList, you can get some goods list data, but I run the node project is on localhost: 3000, apparent across domains.

We handle this differently depending on the framework we use for the project.

1, NodeJS + Express + HTTP-proxy-Middleware plug-in proxy

For Express projects, you can use http-proxy-Middleware, a plug-in designed to proxy front-end requests to other servers.

It’s simple to use. You can check out github’s website at github.com/chimurai/ht…

First you need to install the plugin in your Express project:

npm install --save-dev http-proxy-middleware
Copy the code

Then set the proxy in app.js (as shown in the following example) :

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use('/zhuiszhu', proxy({target: 'http://39.105.136.190:3000/'.changeOrigin: true}));
app.listen(3000); 
Copy the code

When you send the Ajax request again later in the project, you can see that the data is received.

$.ajax({
    url: '/zhuiszhu/goods/getList'.type: 'GET'.success(res){}});Copy the code

Webpack-dev-server agent

We often use WebPack as a front-end automated build tool when developing vUE projects, and also use the Webpack-dev-server plug-in, so you can refer to Webpack-dev-server to configure cross-domain solutions.

Webpack-dev-server is a small NodeJS server that is based on the Express framework and is used to monitor and package and compile static resources in real time. One of the properties is proxy, which is used to configure the proxy request interface.

All you need to do is set devServer in webpack.config.js as follows:

devServer: {
        port: 3000.inline: true.proxy: {
            "/zhuiszhu": {
                target: "http://39.105.136.190:3000/".changeOrigin: true  // Must be set to true for proper proxy}}},Copy the code

Webpack devServer.proxy uses the very powerful HTTP-proxy-middleware package, so it’s essentially the same.

JSONP

The basic idea behind JSONP is that a web page requests JSON data from the server by adding a

For example, when the page resource is loaded, get the cross-domain data and specify the name of the callback function foo:

window.onload = function () {
    var script = document.createElement("script");
    script.setAttribute("type"."text/javascript");
    script.src = "http://bbb.com?callback=foo; document.body.appendChild(script); }; foo(data) { console.log(data); // data = data obtained across domains}Copy the code

On the server side, we need to put the data into the parameters of the function foo:

foo('hello world')
Copy the code

Note the following when using JSONP:

1. The callback function must be configured on the back end. 2. Only GET requests can be sent.

WebSocket

WebSocket is a communication protocol that uses WS :// (non-encrypted) and WSS :// (encrypted) as protocol prefixes. This protocol does not implement the same origin policy, as long as the server supports it, it can be used for cross-source communication.

Since there is a field Origin in the WebSocket request, it indicates the request source (Origin) of the request, that is, the domain name from which the request is sent.

It is because of the Origin field that WebSocket does not implement the same Origin policy. Because the server can determine whether to permit this communication based on this field.

CORS

CORS stands for Cross-Origin Resource Sharing and allows any type of request compared to JSONP.

CORS requires both browser and server support. Currently, all browsers support this function. The value of Internet Explorer cannot be lower than IE10.

The entire CORS communication process is completed automatically by the browser without user participation. For developers, CORS communication is no different from the same source AJAX communication; the code is exactly the same. Once the browser realizes that the AJAX request is cross-source, it automatically adds some additional header information and sometimes an additional request, but the user doesn’t notice.

Therefore, the key to CORS communication is the server. As long as the server implements the CORS interface, it can communicate across sources.

conclusion

To conclude, if you are accessing the resources of another server, and JSONP is not set, WebSocket whitelist is not open, and CORS interface is not set, then the only option is to use your own server for reverse proxy.

Refer to the link

[1] browser same-origin policy and avoid method: www.ruanyifeng.com/blog/2016/0… [2] CORS cross-domain resources sharing a: www.ruanyifeng.com/blog/2016/0… [3] Express Framework: github.com/Daotin/Web/… [4] HTTP proxy – middleware: github.com/chimurai/ht…


For more exciting content, follow me for more front-end technology and personal growth related content, I’m sure interesting people will meet! Original is not easy, if you feel helpful, also welcome to like, share, add collection!