![]() |
The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources. Project Setup and Module Installation: Step 1: Create a Node.js application and name it gfg-cors using the following command. mkdir horje && cd horje Step 2: Install the dependency modules using the following command. npm i express cors Step 3: Create a client directory and server.js file in the root directory. Then create index.html and script.js in the client directory. Project Directory: It will look like this. ![]() Example: This is the code inside the index.html and script.js file.
As we are done with the basic file of codes, now move to the main topic and see how to allow CORS in Express Enabling CORS for all routes: If you want to allow the selected origins to access your site then you need to configure cors as shown below. Syntax: const cors = require('cors') Example: Enabling CORS for all routes of server, the new index.js will like:
Step to run the application: Run the server.js using the following command. node server.js Output: ![]() CORS for a specified route: But there might be the case where only a certain number of unknown origins should be allowed to access resources from our server, and we need to protect our server from the potential intruder(any URL not following same-origin policy) due to confidentiality. Here we will enable CORS requests for a certain number of origins as shown below :}); Syntax: let corsOptions = {
Step to run the application: Run the server.js using the following command. node server.js Output: ![]() |
Reffered: https://www.geeksforgeeks.org
Express.js |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |