InterviewSolution
| 1. |
How to allow CORS in Express.js? Explain with an example. |
|
Answer» CORS stands for Cross-Origin Resource Sharing. It is enabled in the browser by default and because of it a client running on a different network, cannot access the server running on a different network. Here’s an example. First, we will have our Node runtime installed and created using npm init -y. We will ALSO install express and cors in our Node.js app. Now, we will have a simple Express server in which we are sending an array of objects to the client, when coming to home root. First start the node server by running node index.js from the terminal and navigate to http://localhost:3000/ and we will get the array of objects back. This is allowed because our server and client - both are in localhost. Now, to make the request from a different client network, we have to go to some other SITE. We are going to https://www.knowledgehut.com/ and opening the console. Here, we will be using the inbuilt fetch api to GOTO the server endpoint at 3000. Notice that we are getting a CORS ERROR and not able to get the data. In order to allow REQUESTS to our server endpoint from knowledgehut.com, we need to add it in cors middleware. We have already installed cors earlier, so we are importing it first. Now, when we go back to knowledgehut.com, and give the same fetch request we will get the data back successfully. |
|