NodeJS | CORS | #19
What is CORS and How Does It Work?
Introduction to CORS
- The session begins with an introduction to a new topic: CORS (Cross-Origin Resource Sharing). The speaker emphasizes the importance of understanding this concept in web development.
Practical Example of API Integration
- The speaker demonstrates a project with various endpoints tested using Thunder Client, showcasing how they function correctly.
- A new application is created in Visual Studio Code, featuring HTML and CSS, which will interact with the previously developed API.
Setting Up the HTML Application
- The HTML page structure is established for a separate project that will consume the API. This highlights the integration capability between different systems.
- Instead of performing calculations directly within this new application, it will send data to the API for processing, illustrating a clear separation of concerns.
JavaScript Functionality Implementation
- The speaker assigns IDs to input fields in the HTML document for easy access via JavaScript.
- A JavaScript function named
somaris created and linked to a button click event, demonstrating basic interactivity without frameworks.
Making API Calls Using Fetch
- The URL for making requests to the API is constructed dynamically by combining user inputs from two text fields.
- An explanation follows on how to use the Fetch API in pure JavaScript to simulate requests similar to those made through Thunder Client.
Handling Responses from Fetch Requests
- When using
fetch, it's important to handle asynchronous responses properly; thus,awaitis used within an async function.
- The response object contains valuable information such as status and timing metrics, emphasizing that network calls are not instantaneous.
Accessing JSON Data from Responses
- After receiving a response, accessing JSON data allows retrieval of specific information returned by the API.
Understanding API Calls and CORS Issues
Setting Up the Code
- The speaker discusses using
document.getElementByIdto manipulate HTML elements, specifically setting inner text with a variable namedsoma, ensuring it is converted to text format.
- The code primarily involves HTML, CSS, and JavaScript. The speaker emphasizes that calculations are not performed directly in the code but rather through an API call.
Debugging API Responses
- An error (404) occurs when attempting to access the API due to a change in its URL. This indicates a problem with the API endpoint.
- After refreshing and retrying, another error appears indicating that the URL may be incorrectly formatted, suggesting issues within the code itself.
Testing Variables
- The speaker checks variables
N1andN2by displaying alerts to ensure they hold expected values before proceeding further.
- An alert for the URL is also added for verification purposes; however, issues persist with fetching data from the API.
Addressing CORS Errors
- To resolve potential conflicts, the speaker decides to pass URLs directly into fetch calls since GET is the default method.
- A new error related to CORS (Cross-Origin Resource Sharing) arises after making adjustments. This indicates restrictions on cross-domain requests.
Understanding CORS
- CORS errors occur when trying to access resources from a different domain than where your site is hosted. It prevents unauthorized access between different domains.
- The explanation of CORS highlights its purpose: protecting against attacks by restricting how resources can be shared across different origins.
Enabling CORS in APIs
- To allow cross-origin requests, changes must be made on the server-side of the API rather than within client-side code.
- The process involves installing a package called 'cors' via npm and importing it into your server setup.
Finalizing Setup and Testing
- After enabling CORS by adding it to server middleware, testing shows successful communication with the API as responses are received correctly.
- A successful addition of two numbers (5 + 8 = 13), confirms that data retrieval from the API works as intended without any further errors related to CORS.
Monitoring Network Requests
Integration of API with Applications
Overview of API Integration
- The speaker discusses the capability of integrating their program with various applications, such as mobile apps or websites. This integration allows for not just basic functions like addition but any other functionalities provided by the API.
- A challenge is presented to the audience, encouraging them to create their own applications using the same code and integrate it with the API.
Code Presentation
- The speaker briefly presents the code used for integration, suggesting that viewers can pause to review it.
- Additional CSS is mentioned, which enhances the visual appeal of the application; however, customization of CSS is left up to the audience.