Ajax solves cross-domain problem by setting CORS response header to achieve cross-domain case study

Ajax solves cross-domain problem by setting CORS response header to achieve cross-domain case study

1. Set CORS response header to achieve cross-domain

Cross-Origin Resource Sharing (CORS)

1.1 What is CORS

CORS (Cross-Origin Resource Sharing), cross-origin resource sharing. CORS is the official cross-domain solution. Its feature is that it does not require any special operations on the client and is completely processed on the server. It supports get and post requests. The Cross-Origin Resource Sharing standard adds a set of HTTP header fields that allow servers to declare which origins have access to which resources through browsers.

1.2 How does CORS work?

CORS sets a response header to tell the browser that the request is allowed to cross domains. After receiving the response, the browser will release the response.

1.3 What is CORS used for?

insert image description here

ajaxDemo.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>

<body>
    <button>Send Request</button>
    <div id="result"></div>
    <script>
        const btn = document.querySelector('button');

        btn.onclick = function () {
            //1. Create object const x = new XMLHttpRequest();
            //2. Initialization settings x.open("GET", "http://127.0.0.1:8080/cors-server");
            //3. Send x.send();
            //4. Bind event x.onreadystatechange = function () {
                if (x.readyState === 4) {
                    if (x.status >= 200 && x.status < 300) {
                        document.getElementById('result').innerText = x.response;
                    }
                }
            }
        }
    </script>
</body>

</html>

insert image description here

server.js

//1. Import express
const express = require('express');

//2. Create application object const app = express();
 
//3. Create routing rules // request is the encapsulation of the request message // response is the encapsulation of the response message app.all('/cors-server', (request, response)=>{
    //Set the response header response.setHeader("Access-Control-Allow-Origin", "*"); // Allow all cross-domain requests* 
    // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500"); // Allow specified requests to cross domains // response.setHeader("Access-Control-Allow-Headers", '*'); // Allow custom request header tags // response.setHeader("Access-Control-Allow-Method", '*'); // Allow all requests to cross domains *
    // response.setHeader("Access-Control-Allow-Method", 'get'); // Allow get requests to cross domain response.send('hello CORS');
});


//4. Listening port to start service app.listen(8080, () => {
    console.log("The service has been started, port 8080 is listening....");
});

Start the service nodemon server.js

insert image description here

Running results:

insert image description here

This is the end of this article about Ajax cross-domain solution and setting CORS response header to achieve cross-domain case details. For more relevant Ajax cross-domain solution content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Three-level linkage provincial and municipal ajax code
  • JSON, AJAX, Maven Basics
  • Ajax login verification implementation code
  • Ajax realizes the linkage between provinces, cities and districts
  • jQuery+Ajax to achieve simple paging effect
  • Preliminary implementation of Ajax (using vscode+node.js+express framework)
  • How to use AJAX to obtain Django backend data
  • Detailed explanation of the parsererror error case in JavaScript solution in ajax

<<:  Implementation of docker redis5.0 cluster cluster construction

>>:  Migrate virtual machines between VMware Workstation and vSphere (picture and text)

Recommend

Detailed process of configuring Https certificate under Nginx

1. The difference between Http and Https HTTP: It...

js to make a simple calculator

This article shares the specific code of making a...

jQuery simulates picker to achieve sliding selection effect

This article shares the specific code of jQuery t...

How to use custom tags in html

Custom tags can be used freely in XML files and HT...

jQuery treeview tree structure application

This article example shares the application code ...

Detailed explanation of JavaScript prototype chain

Table of contents 1. Constructors and instances 2...

How to use flat style to design websites

The essence of a flat website structure is simpli...

MySQL Error 1290 (HY000) Solution

I struggled with a problem for a long time and re...

User needs lead to marketing-oriented design

<br />For each of our topics, the team will ...

How to connect to MySQL using C++

C++ connects to MySQL for your reference. The spe...

Java uses Apache.POI to export HSSFWorkbook to Excel

Use HSSFWorkbook in Apache.POI to export to Excel...