Home Web Front-end JS Tutorial How to implement cross-domain ajax requests using CORS through the Koa2 framework

How to implement cross-domain ajax requests using CORS through the Koa2 framework

Jun 01, 2018 am 11:17 AM
cors koa2 use

This article mainly introduces the Koa2 framework's use of CORS to complete cross-domain ajax requests. Now I share it with you and give you a reference.

There are many ways to implement cross-domain ajax requests, one of which is to use CORS, and the key to this method is to configure it on the server side.

This article only explains the most basic configuration that can complete normal cross-domain ajax response (I don't know how to do in-depth configuration).

CORS divides requests into simple requests and non-simple requests. It can be simply thought that simple requests are get and post requests without additional request headers, and if it is a post request, the request format cannot be application. /json (because I don’t have a deep understanding of this area. If there is an error, I hope someone can point out the error and suggest modifications). The rest, put and post requests, requests with Content-Type application/json, and requests with custom request headers are non-simple requests.

The configuration of a simple request is very simple. If you only need to complete the response to achieve the goal, you only need to configure the Access-Control-Allow-Origin in the response header.

If we want to access the http://127.0.0.1:3001 domain name under the http://localhost:3000 domain name. You can make the following configuration:

app.use(async (ctx, next) => {
 ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
 await next();
});
Copy after login

Then use ajax to initiate a simple request, such as a post request, and you can easily get the correct response from the server.

The experimental code is as follows:

$.ajax({
  type: 'post',
  url: 'http://127.0.0.1:3001/async-post'
 }).done(data => {
  console.log(data);
})
Copy after login

Server-side code:

router.post('/async-post',async ctx => {
 ctx.body = {
 code: "1",
 msg: "succ"
 }
});
Copy after login

Then you can get the correct response information.

If you look at the header information of the request and response at this time, you will find that the request header has an extra origin (there is also a referer for the URL address of the request), and the response header has an extra Access- Control-Allow-Origin.

Now you can send simple requests, but you still need other configurations to send non-simple requests.

When a non-simple request is issued for the first time, two requests will actually be issued. The first one is a preflight request. The request method of this request is OPTIONS. Whether this request passes determines whether this request is passed. Whether the type of non-simple request can be successfully responded to.

In order to match this OPTIONS type request on the server, you need to make a middleware to match it and give a response so that this preflight can pass.

app.use(async (ctx, next) => {
 if (ctx.method === 'OPTIONS') {
 ctx.body = '';
 }
 await next();
});
Copy after login

This way the OPTIONS request can pass.

If you check the request header of the preflight request, you will find that there are two more request headers.

Access-Control-Request-Method: PUT
Origin: http://localhost:3000
Copy after login

Negotiate with the server through these two header information to see if the server response conditions are met.

It’s easy to understand. Since the request header has two more pieces of information, the response header should naturally have two corresponding pieces of information. The two pieces of information are as follows:

Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: PUT,DELETE,POST,GET
Copy after login
Copy after login

The first piece of information and origin The same therefore passes. The second piece of information corresponds to Access-Controll-Request-Method. If the request method is included in the response method allowed by the server, this piece of information will also pass. Both constraints are met, so the request can be successfully initiated.

So far, it is equivalent to only completing the pre-check and not sending the real request yet.

Of course the real request also successfully obtained the response, and the response header is as follows (omitting unimportant parts)

Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: PUT,DELETE,POST,GET
Copy after login
Copy after login

The request header is as follows:

Origin: http://localhost:3000
Copy after login

This is very obvious, The response header information is set by us on the server, so this is the case.

The client does not need to send the Access-Control-Request-Method request header because it has been pre-checked just now.

The code for this example is as follows:

$.ajax({
   type: 'put',
   url: 'http://127.0.0.1:3001/put'
  }).done(data => {
   console.log(data);
});
Copy after login

Server code:

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
  ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
  await next();
});
Copy after login

At this point we have completed the basic configuration that can correctly perform cross-domain ajax response, and some can be further configured. s things.

For example, so far, every non-simple request will actually issue two requests, one for preflight and one for real request, which results in a loss of performance. In order not to send a preflight request, you can configure the following response headers.

Access-Control-Max-Age: 86400
Copy after login

The meaning of this response header is to set a relative time from the moment the non-simple request passes the test on the server side, when the elapsed time in milliseconds is less than Access-Control-Max-Age , there is no need to perform preflight, and you can directly send a request.

Of course, there is no preflight for simple requests, so this code is meaningless for simple requests.

The current code is as follows:

app.use(async (ctx, next) => {
 ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
 ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
 ctx.set('Access-Control-Max-Age', 3600 * 24);
 await next();
});
Copy after login

Up to now, you can respond to cross-domain ajax requests, but the cookies under this domain will not be carried in the request header. If you want to bring the cookie to the server and allow the server to further set the cookie, further configuration is required.

In order to facilitate subsequent detection, we set two cookies under the domain name http://127.0.0.1:3001 in advance. Be careful not to mistakenly set the cookie to Chinese (I just set it to Chinese, and the result was an error. I couldn't find the cause of the error for a long time)

Then we have to do two steps. The first step is to set the response header Access-Control-Allow. -Credentials is true, and then sets the withCredentials attribute of the xhr object to true on the client.

The client code is as follows:

$.ajax({
   type: 'put',
   url: 'http://127.0.0.1:3001/put',
   data: {
    name: '黄天浩',
    age: 20
   },
   xhrFields: {
    withCredentials: true
   }
  }).done(data => {
   console.log(data);
  });
Copy after login

The server code is as follows:

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
  ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
  ctx.set('Access-Control-Allow-Credentials', true);
  await next();
});
Copy after login

这时就可以带着cookie到服务器了,并且服务器也可以对cookie进行改动。但是cookie仍是http://127.0.0.1:3001域名下的cookie,无论怎么操作都在该域名下,无法访问其他域名下的cookie。

现在为止CORS的基本功能已经都提到过了。

一开始我不知道怎么给Access-Control-Allow-Origin,后来经人提醒,发现可以写一个白名单数组,然后每次接到请求时判断origin是否在白名单数组中,然后动态的设置Access-Control-Allow-Origin,代码如下:

app.use(async (ctx, next) => {
 if (ctx.request.header.origin !== ctx.origin && whiteList.includes(ctx.request.header.origin)) {
  ctx.set('Access-Control-Allow-Origin', ctx.request.header.origin);
  ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
  ctx.set('Access-Control-Allow-Credentials', true);
  ctx.set('Access-Control-Max-Age', 3600 * 24);
 }
 await next();
});
Copy after login

这样就可以不用*通配符也可匹配多个origin了。

注意:ctx.origin与ctx.request.header.origin不同,ctx.origin是本服务器的域名,ctx.request.header.origin是发送请求的请求头部的origin,二者不要混淆。

最后,我们再稍微调整一下自定义的中间件的结构,防止每次请求都返回Access-Control-Allow-Methods以及Access-Control-Max-Age,这两个响应头其实是没有必要每次都返回的,只是第一次有预检的时候返回就可以了。

调整后顺序如下:

app.use(async (ctx, next) => {
 if (ctx.request.header.origin !== ctx.origin && whiteList.includes(ctx.request.header.origin)) {
  ctx.set('Access-Control-Allow-Origin', ctx.request.header.origin);
  ctx.set('Access-Control-Allow-Credentials', true);
 }
 await next();
});

app.use(async (ctx, next) => {
 if (ctx.method === 'OPTIONS') {
  ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
  ctx.set('Access-Control-Max-Age', 3600 * 24);
  ctx.body = '';
 }
 await next();
});
Copy after login

这样就减少了多余的响应头。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

webpack打包js的方法

vue 简单自动补全的输入框的示例

angular5 httpclient的示例实战

The above is the detailed content of How to implement cross-domain ajax requests using CORS through the Koa2 framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use GitLab for project document management How to use GitLab for project document management Oct 20, 2023 am 10:40 AM

How to use GitLab for project document management 1. Background introduction In the software development process, project documents are very important information. They can not only help the development team understand the needs and design of the project, but also provide reference to the testing team and customers. In order to facilitate version control and team collaboration of project documents, we can use GitLab for project document management. GitLab is a version control system based on Git. In addition to supporting code management, it can also manage project documents. 2. GitLab environment setup First, I

How to use Flask-CORS to achieve cross-domain resource sharing How to use Flask-CORS to achieve cross-domain resource sharing Aug 02, 2023 pm 02:03 PM

How to use Flask-CORS to achieve cross-domain resource sharing Introduction: In network application development, cross-domain resource sharing (CrossOriginResourceSharing, referred to as CORS) is a mechanism that allows the server to share resources with specified sources or domain names. Using CORS, we can flexibly control data transmission between different domains and achieve safe and reliable cross-domain access. In this article, we will introduce how to use the Flask-CORS extension library to implement CORS functionality.

How to use CORS cross-domain request in PHP-Slim framework? How to use CORS cross-domain request in PHP-Slim framework? Jun 03, 2023 am 08:10 AM

In web development, cross-domain requests are a common problem. This is because browsers have strict restrictions on requests between different domain names. For example, website A's front-end code cannot send requests directly to website B's API unless website B allows cross-domain requests. In order to solve this problem, CORS (Cross-Origin Resource Sharing) technology emerged. This article will introduce how to use CORS cross-domain requests in the PHP-Slim framework. 1. What is CORSCORS? It is a mechanism that adds some amounts to the corresponding HTTP header.

What does TikTok recommended video mean? How to use Douyin to recommend videos? What does TikTok recommended video mean? How to use Douyin to recommend videos? Mar 27, 2024 pm 03:01 PM

As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this

How to build a RESTful API and implement CORS using Golang? How to build a RESTful API and implement CORS using Golang? Jun 02, 2024 pm 05:52 PM

Create a RESTful API and implement CORS: Create the project and install dependencies. Set up HTTP routing to handle requests. Enable cross-origin resource sharing (CORS) using the middlewareCORS middleware. Apply CORS middleware to the router to allow GET and OPTIONS requests from any domain.

Use CORS in Beego framework to solve cross-domain problems Use CORS in Beego framework to solve cross-domain problems Jun 04, 2023 pm 07:40 PM

With the development of web applications and the globalization of the Internet, more and more applications need to make cross-domain requests. Cross-domain requests are a common problem for front-end developers, and it can cause applications to not work properly. In this case, one of the best ways to solve the problem of cross-origin requests is to use CORS. In this article, we will focus on how to use CORS in the Beego framework to solve cross-domain problems. What is a cross-domain request? In web applications, cross-domain requests refer to requests from a web page of one domain name to another

How to use Go language for concurrent programming? How to use Go language for concurrent programming? Jun 10, 2023 am 10:33 AM

With the continuous development of computer hardware, the CPU cores in the processor no longer increase the clock frequency individually, but increase the number of cores. This raises an obvious question: How to get the most out of these cores? One solution is through parallel programming, which involves executing multiple tasks simultaneously to fully utilize the CPU cores. This is a unique feature of the Go language. It is a language designed specifically for concurrent programming. In this article, we will explore how to leverage Go language for concurrent programming. Coroutines First, we need to understand

What are the ways springboot solves CORS cross-domain issues? What are the ways springboot solves CORS cross-domain issues? May 13, 2023 pm 04:55 PM

1. Implement the WebMvcConfigurer interface @ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{/***Add cross-domain support*/@OverridepublicvoidaddCorsMappings(CorsRegistryregistry){//The path that allows cross-domain access '/**' represents all methods of the application registry.addMapping("/** ")//Sources that allow cross-domain access'*

See all articles