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

Some references about colors in HTML

In HTML, colors are represented in two ways. One i...

mysql obtains statistical data within a specified time period

mysql obtains statistical data within a specified...

Analysis of MySQL latency issues and data flushing strategy process

Table of contents 1. MySQL replication process 2....

How to add automatic completion commands for docker and kubectl on Mac

Introduction to kubectl kubectl is a command line...

Vue realizes the function of book shopping cart

This article example shares the specific code of ...

Docker Machine in-depth explanation

Differences between Docker and Docker Machine Doc...

WeChat applet learning wxs usage tutorial

What is wxs? wxs (WeiXin Script) is a scripting l...

JS achieves five-star praise case

This article shares the specific code of JS to ac...

JavaScript function syntax explained

Table of contents 1. Ordinary functions 2. Arrow ...

Solution to Nginx session loss problem

In the path of using nginx as a reverse proxy tom...

Table of CSS Bugs Caused by hasLayout

IE has had problems for a long time. When everyone...

N ways to achieve two-column layout with CSS

1. What is a two-column layout? There are two typ...

Linux Autofs automatic mount service installation and deployment tutorial

Table of contents 1. Introduction to autofs servi...