preface

Front-end cross-domain is a very common thing. How to solve the cross-domain problem is the basic knowledge that every front-end programmer needs to master. Let me talk about front-end cross-domain and the solution

The same-origin policy

The same-origin policy is an important security policy enforced on browsers to restrict non-same-origin documents or scripts from interacting. It can help block malicious documents and reduce the number of vectors that can be attacked.

So what is the same origin policy?

Same-origin refers to the same IP address, same port number, and same protocol. If one of them is different, it is non-same-origin, that is, cross-domain, and cannot be accessed by the browser

There are several ways in which the front end can solve cross-domain problems

Here are some common front-end solutions to cross – domain problems

1. JSONP

(1) Basic Principles:

Web pages are not constrained by the same-origin policy when calling script tags. If you write the interface in the SRC attribute of the Script tag and use a callback function to accept parameters, you can achieve front-end cross-domain

(2) Directly on the code

/ / get the dom
var app = document.getElementById("app")
// Create a label
var script = document.createElement("script")
// Set the SRC attribute
script.src = "http://*********? callback=showData"
app.appendChild(script)
// Process data
showData(obj){
 // obj is the returned data
}
// Delete the label
app.removechild(script)
Copy the code

(3) jquery implements JSONP call

 $.ajax({
   url: "http://********".dataType: "jsonp".success: function( response ) {
     if(response === 'success'){
       amount.innerText = amount.innerText - 1}}})Copy the code

2. Webpack agent

(1) If it is in a Webpack project, webpack agent is generally used. Data request by Webpack is not cross-domain, nor is it cross-domain request by local browser, thus solving the cross-domain problem.

The configuration is as follows:

  module.exports = {
    dev: {
      // Paths
      assetsSubDirectory: 'static'.assetsPublicPath: '/'.proxyTable: {
        '/api': {
          target: 'https://*****.xxxxxxxx.com'./ / source
          pathRewrite: {'^/api': '/api'}, // Override the method
          changeOrigin: true.// Whether cross-domain,
          secure: false.// Set a proxy that supports HTTPS}},... }Copy the code

conclusion

There are many ways to cross the domain front end, here I will introduce you to the most common two methods, if you want to know about other cross domain methods can give me a message, I will continue to update.