Yue, four is the peak season, the job interview of cross-domain request scheme in the front-end eight-part essays, for cross-domain scene understanding is necessary, in terms of current combining with project practice, cross-domain request carry cookies in the practice process of understanding can help us fully understand the front-end configuration of some potential problems setting up the cross domain, These problems say big or small, but it is very common in daily development, can be said in any front-end project initialization will encounter, through demo verification, we can solve the following problems:

1. How to configure the withCredentials in axios? 2. Learn to set the 'access-control-allow-origin' 'access-control-allow-credentials' attributes and configure them. 3. Learn to solve the problem of cross-domain request carrying cookie of source site; .Copy the code

We will build the solution by thinking as follows:

  • First of all, we use express framework to build the first service A (http://localhost:8000), running on port 8000.
  • A service hosts the index.html(used to send network requests on the front-end page) file, which is equivalent to enabling a cognate front-end service on service A;
  • Write a route to handle the request in service A, and plant a cookie when loading the index. HTML page (here the cookie is carried when requesting service B);
  • Then use Express to build the second service B (http://localhost:8001), running on port 8001;
  • The index.html page hosted by service A requests service B and then passes the cookie. The whole process is A simple cross-domain request with cookie

First initialize a Node project, introduce express framework, first build a service:

// express/app01.js

const express = require('express');
const app = express();

// Access front-end cleaning through the IP+ port + /static/index.html of the Express service
app.use('/static', express.static("public"));

// Set the cookie information after the user logs in successfully
app.get('/login'.(req, res) = > {
  res.cookie('user'."kobebryant", {maxAge: 200000.httpOnly: true});
  res.json({code: 0.message: 'login success'});
})

app.get("/user".(req, res) = > {
  const user = req.headers.cookie.split("=") [1];
  res.json({code :0, user});
})

app.listen('8000'.() = > {
  console.log('====== app01 running =======')})Copy the code

Front-end code in a service:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, ">< title>Document</title> </head> <script SRC ="./axios.min.js"></script> <body> <button Id ="button01" </button> <button ID ="button02"> </button> </body> <script> const button01 = document.querySelector('#button01'); const button02 = document.querySelector('#button02'); / / simulation initialization and obtain a cookie axios. Get (" http://localhost:8000/login ", {}). Then (= > {(res). The console log (' res = = = = = > 'res); }) / / button01 carry cookies homologous request button01. The onclick = () = > {axios. Get (" http://localhost:8000/user ", {}).then( (res) =>{ console.log('res =====>', res); })} / / button02 carry cookies cross-domain request button02. The onclick = () = > {axios ({url: "http://localhost:8001/service", method: "get" }).then( (res) =>{ console.log('res =====>', res); }) } </script> </html>Copy the code

B Server code:

const express = require('express');
const app = express();

app.get("/service".(req, res) = > {
  res.json({code :0.msg: 'This is the response to the cross-domain request'});
})

app.listen('8001'.() = > {
  console.log('====== app02 running =======')})Copy the code

Start services A and B, then enter the URL in the webpage: http://localhost:8000/static/index.html, this time the F12 open the console: We can see that a login request is sent and a cookie is set. Then we click the send same-origin request button on the page, and we can see that a user request is sent and cookie is already carried, indicating that the same-origin request can normally carry cookie information. Next comes the exciting picture, we click the send cross-domain request button, there is a cross-domain request error. Let’s start solving the problem of cross-domain cookie portability:

    1. Set the withCredentials attribute of the Request object to true at the time of the front-end request

XMLHttpRequest withCredentials attribute is a Boolean type, It indicates whether a qualification such as cookies, Authorization Headers, or TLS client certificates should be used to create a cross-site Access-control request. Using the withCredentials attribute at the same site is invalid. If withCredentials are not set to true before sending XMLHttpRequest requests from other domains, then it cannot set cookie values for its own domain. Third-party cookies obtained by setting withCredentials to True will still enjoy the same origin policy.

Modify the cross-domain request in the index.html code:

 // Button02 carries cookies for cross-domain requests
  button02.onclick = () = > {
    axios({
      url: "http://localhost:8001/service".withCredentials: true.method: "get"
    }).then( (res) = >{
      console.log('res =====>', res); })}Copy the code

The access-Control-allow-Origin attribute of the header must be set. The access-Control-Allow-Origin attribute of the header must be set to the access-Control-allow-origin attribute.

    1. Set access-Control-allow-Origin on the server

We modify the code of the b(app02.js) service:

// Add to all routes, All ('*', (req,res,next) => {res.header(" access-Control-allow-origin ", "http://localhost:8000"); next(); })Copy the code

The Access control-allow-credentials attribute should be set to true when you send the cross-domain request again.

  • 3. Set access-control-allow-credentials on the server

Modify the b service code again (need to run again after each change) :

// Add to all routes, All ('*', (req,res,next) => {res.header(" access-Control-allow-origin ", "http://localhost:8000"); res.header("Access-Control-Allow-Credentials", true); next(); })Copy the code

As you can see, the cross-domain request has been successfully requested and has returned data! It also carries the cookie of A’s service. To sum up, when front-end K cross-domain requests carry cookie authentication, configure “withCredentials”: true in the Request object; Configure “access-Control-allow-origin” in the response header on the server. “http://xxx”, configure “access-Control-allow-credentials “, “true” in the response header.