![]() |
Cross-Origin Resource Sharing (CORS) is a browser-level security feature that disallows the requests (by default) to be made between different origins, i.e., a frontend client requesting a backend server that is deployed on a different origin or domain. We can bypass or allow the requests that are made cross-origin with the help of different methods. In this article, we will learn how to handle CORS in JavaScript with the help of some code examples. Handling CORS using Express serverIn this approach, we will create and use the NodeJS and expressJS servers to handle the CORS requests made to them. We can set the “Access-Control-Allow-Origin” in the response object header for every request that is sent to it, to allow the requests from any origin. Example: Setup the application: First, install the required packages for the application using the below steps: npm init -y Create the index.js file: Now, create the index.js file, and setup the express server. In the same file, allow the “Access-Control-Allow-Origin” response header to every requests that are made to it.
Run the express API server Start the server using the below command npm start Creating a vanilla JS application to consume the above API server endpoint Run the below commands inside the terminal to create a basic structure for creating our javascript application mkdir cors-test The project structure would look like below: Project structure: Now, modify the index.html file in the project structure to fetch the data from the express API server, and display that data in the UI. Filename: index.html
Run the vanilla javascript application: Now, open the index.html file created above, to see the output in the browser. Output: |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |