I am a pure front-end employee. I just joined Egg for a month, but NodeJS is a white. Thanks to the elegance and strength of Egg, the company’s project is progressing very smoothly. My personal experience with egg is the same as vue, pure and beautiful.

Cross-domain problem

It is inevitable to consider cross-domain issues when writing servers. Egg-cors plug-in provides origin configuration, which provides convenience for everyone.

An egg – cors open:



An egg – cors configuration:



This is one of the most commonly used plug-ins to solve cross-domain problems.

However, in my actual project, some requirements cannot be met, so I think egg-CORS has certain limitations in configuration.

  1. The orgin parameter can only be set to a domain name, or ‘*’.
  2. When set to ‘*’ to allow all domain names to cross domains, the request with withCredentials: true still has a cross-domain problem.

In order to solve the above problems, DECIDED to do their own plugin egg-Origin. This is middleware and the code is very simple.



Yes, the above is all to the code 😅😅

Setthis.ctx.response. set(‘ access-Control-allow-origin ‘, origin); In this way, you can configure the cross-domain whitelist based on your requirements.

Usage:

Use the same as egg-cors

An egg – origin to open:



An egg – origin configuration:



The whiteList parameter can be set to a domain name or [‘ * ‘]. It must be an array, so as to maintain the same configuration convention as egg-cors.


The plugin actually relies on egg-cors, which I added to the default configuration



Egg-origin whitelist overrides the egg-cors configuration. Standing on the shoulders of giants, to see further, thanks to the giant.

Late Iteration plan

At present, only the full matching mode is supported. The next iteration plan includes the configuration of level 1 domain names, all sub-domain names can be used, and the “blacklist” configuration will be added to filter certain domain names.

If you find it useful, please give a little star 👍👍 github.com/temool/egg-…