官术网_书友最值得收藏!

CORS in Express.js

We want our GraphQL API to be accessible from any website, app, or system. A good idea might be to build an app or offer the API to other companies or developers so that they can use it. When using APIs via Ajax, the main problem is that the API needs to send the correct Access-Control-Allow-Origin header.

For example, if you build the API, publicize it under https://api.example.com, and try to access it from https://example.com without setting the correct header, it won't work. The API would need to set at least example.com inside the Access-Control-Allow-Origin header to allow this domain to access its resources. It seems a bit tedious, but it makes your API open to cross-site requests which you should always be aware of.

Allow CORS (Cross-origin resource sharing) requests with the following command to the index.js file:

app.use(cors());

This command handles all of the problems we usually have with cross-origin requests at once. It merely sets a wildcard with * inside of Access-Control-Allow-Origin, allowing anyone from anywhere to use your API, at least in the first instance. You can always secure your API by offering API keys or by only allowing access to logged-in users. Enabling CORS only allows the requesting site to receive the response.

Furthermore, the command also implements the OPTIONS route for the whole application.

The OPTIONS method or request is made every time we use Cross-origin resource sharing. This action is what's called a preflight request, which ensures that the responding server trusts you. If the server does not respond correctly to the OPTIONS preflight, the actual method, such as POST, will not be made by the browser at all.

Our application is now ready to serve all routes appropriately and respond with the right headers.

We can move on now and finally set up a GraphQL server.

主站蜘蛛池模板: 平泉县| 锡林浩特市| 乌拉特中旗| 东明县| 遂溪县| 马公市| 惠来县| 通城县| 萨嘎县| 绥芬河市| 铅山县| 兴安县| 隆回县| 锡林浩特市| 平乐县| 永嘉县| 富宁县| 满洲里市| 柳林县| 凤阳县| 桂平市| 金沙县| 孙吴县| 西盟| 维西| 清河县| 治多县| 商南县| 嘉黎县| 土默特左旗| 平邑县| 永和县| 洛南县| 垣曲县| 乐业县| 商城县| 紫金县| 灵武市| 元阳县| 博湖县| 丁青县|