search
HomeWeb Front-endJS TutorialDetailed introduction to CORS cross-domain resource sharing (with code)

Detailed introduction to CORS cross-domain resource sharing (with code)

Mar 12, 2019 pm 04:55 PM
html5javascriptnode.jsfront end

This article brings you a detailed introduction to CORS cross-domain resource sharing (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Understand the same-origin policy

Source (origin)*: It is the protocol, domain name and port number; Same-origin: It means the same source, that is, the protocol, domain name and port are exactly the same; Same-origin policy : The same-origin policy is a security feature of the browser. Client scripts from different origins cannot read or write each other's resources without explicit authorization;

Classification of the same-origin policy:

DOM same-origin policy: For DOM, it is forbidden to operate DOM of different source pages; for example, iframes with different domain names restrict mutual access. XMLHttpRequest Origin Policy: It is prohibited to use XHR objects to initiate HTTP requests to server addresses with different origins.

is not restricted by the same-origin policy:

Links, redirects and form submissions in the page (because after form submission and data submission to the action domain, the page itself has nothing to do with it. It does not care about the request result, and all subsequent operations are handed over to the domain in the action) and will not be restricted by the same-origin policy. The introduction of resources is not restricted, but js cannot read and write loaded content: such as , Detailed introduction to CORS cross-domain resource sharing (with code), embedded in the page,

Why cross-domain restrictions

If there is no DOM same-origin policy: then there will be no research on xss, because your website will not be your website, but Everyone, anyone can write a code to operate your website interface

If there is no XMLHttpRequest origin policy, then CSRF (cross-site request forgery) attacks can be easily carried out:

User After logging into my own website page a.com, the user ID is added to the cookie. The user browsed the malicious page b.com and executed the malicious AJAX request code in the page. b.com initiates an AJAX HTTP request to a.com, and the request will also send the cookie corresponding to a.com by default. a.com extracts the user ID from the sent cookie, verifies that the user is correct, and returns the request data in the response; the data is leaked. And because Ajax is executed in the background, this process is invisible to users. (Attachment) With XMLHttpRequest, can the same-origin policy limit CSRF attacks? Don’t forget that there are also things that are not subject to the same-origin policy: form submission and resource introduction (security issues will be studied in the next issue)

Cross-domain solution

JSONP cross-domain: borrowed from the script tag It is not affected by the browser's same-origin policy and allows cross-domain reference of resources; therefore, script tags can be created dynamically and then the src attribute can be used for cross-domain;

Disadvantages: All websites can get the data, so there is security Sexual issues require both sides of the website to negotiate the identity verification of the basic token. It can only be GET, not POST. Malicious code may be injected and the page content may be tampered with. String filtering can be used to avoid this problem. Server proxy: Browsers have cross-domain restrictions, but servers do not have cross-domain problems, so the server can request resources in the desired domain and then return them to the client. document.domain, window.name, location.hash: Use iframe to solve DOM same-origin policy postMessage: Solve DOM same-origin policy, new solution CORS (cross-domain resource sharing): The key points here

CORS (cross-domain resource sharing)

The standard cross-domain solution provided by HTML5 is a set of control strategies that are followed by browsers and interacts through the HTTP Header; CORS is mainly set through the backend. Configuration items.

CORS is simple to use

As mentioned before, CORS is cross-domain. Well, just set Access-Control-Allow-Origin on the backend: *|[or specific domain name]; first Attempts:

app.use(async(ctx,next) => {
    ctx.set({
        "Access-Control-Allow-Origin": "http://localhost:8088"
})

Found that some requests can succeed, but some still report errors:

Detailed introduction to CORS cross-domain resource sharing (with code)

The request is blocked by the same-origin policy, and the pre-request response does not pass the check: http The response is not ok?

and it is found that the OPTIONS request is sent:

Detailed introduction to CORS cross-domain resource sharing (with code)

It is found that the CORS specification divides the request into two types Type, one is a simple request, the other is a non-simple request with preflight

Simple request and non-simple request

How the browser determines when sending a cross-domain request:

When the browser sends a cross-domain request, it will first determine whether it is a simple request or a non-simple request. If it is a simple request, the server program will be executed first, and then the browser will determine whether it is cross-domain; and for non-simple requests request, the browser will send an OPTIONS HTTP request before sending the actual request to determine whether the server can accept the cross-domain request; if not, the browser will directly prevent the subsequent actual request from occurring. What is a simple request?

The request method is one of the following:

GETHEADPOST

All headers only include the following list (no custom headers):

Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma除此之外都是非简单请求

CORS非简单请求配置须知

正如上图报错显示,对于非简单请求,浏览器会先发送options预检,预检通过后才会发送真是的请求;发送options预检请求将关于接下来的真实请求的信息给服务器:

Origin:请求的源域信息
Access-Control-Request-Method:接下来的请求类型,如POST、GET等
Access-Control-Request-Headers:接下来的请求中包含的用户显式设置的Header列表
服务器端收到请求之后,会根据附带的信息来判断是否允许该跨域请求,通过Header返回信息:
Access-Control-Allow-Origin:允许跨域的Origin列表
Access-Control-Allow-Methods:允许跨域的方法列表
Access-Control-Allow-Headers:允许跨域的Header列表,防止遗漏Header,因此建议没有特殊需求的情况下设置为*
Access-Control-Expose-Headers:允许暴露给JavaScript代码的Header列表
Access-Control-Max-Age:最大的浏览器预检请求缓存时间,单位为s

CORS完整配置

koa配置CORS跨域资源共享中间件:
const cors = (origin) => {
    return async (ctx, next) => {
        ctx.set({
            "Access-Control-Allow-Origin": origin, //允许的源
        })
        // 预检请求
        if (ctx.request.method == "OPTIONS") {
            ctx.set({
                'Access-Control-Allow-Methods': 'OPTIONS,HEAD,DELETE,GET,PUT,POST', //支持跨域的方法
                'Access-Control-Allow-Headers': '*', //允许的头
                'Access-Control-Max-Age':10000, // 预检请求缓存时间
                // 如果服务器设置Access-Control-Allow-Credentials为true,那么就不能再设置Access-Control-Allow-Origin为*,必须用具体的域名
                'Access-Control-Allow-Credentials':true // 跨域请求携带身份信息(Credential,例如Cookie或者HTTP认证信息)
            });
            ctx.send(null, '预检请求')
        } else {
            // 真实请求
            await next()
        }
    }
}

export default cors

现在不管是简单请求还是非简单请求都可以跨域访问啦~

跨域时如何处理cookie

cookie:

我们知道http时无状态的,所以在维持用户状态时,我们一般会使用cookie;cookie每次同源请求都会携带;但是跨域时cookie是不会进行携带发送的;

问题:

由于cookie对于不同源是不能进行操作的;这就导致,服务器无法进行cookie设置,浏览器也没法携带给服务器(场景:用户登录进行登录操作后,发现响应中有set-cookie但是,浏览器cookie并没有相应的cookie)

决解:

浏览器请求设置withCredentials为true即可让该跨域请求携带 Cookie;使用axios配置axios.defaults.withCredentials = true服务器设置Access-Control-Allow-Credentials=true允许跨域请求携带 Cookie“积跬步、行千里”—— 持续更新中~,喜欢的话留下个赞和关注哦!

往期经典好文:

服务器(CentOS)安装配置mongodbKoa日志中间件封装开发(log4js)团队合作必备的Git操作使用pm2部署node生产环境

The above is the detailed content of Detailed introduction to CORS cross-domain resource sharing (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools