avatarKirti K

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4168

Abstract

l-Allow-Origin</code> header in its responses.</p><p id="0cd4"><b>Examples</b></p><p id="6ff8"><b>How to fix it</b></p><ol><li><b>With Express.js Example</b></li></ol><div id="3964"><pre><span class="hljs-comment">// Assuming you're using Express.js for your server</span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>); <span class="hljs-keyword">const</span> app = <span class="hljs-title function_">express</span>();

<span class="hljs-comment">// Add CORS middleware</span> app.<span class="hljs-title function_">use</span>(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =></span> { res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Access-Control-Allow-Origin'</span>, <span class="hljs-string">'*'</span>); <span class="hljs-comment">// Allow requests from any origin</span> res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Access-Control-Allow-Methods'</span>, <span class="hljs-string">'GET, POST, PUT, DELETE'</span>); <span class="hljs-comment">// Allow specific HTTP methods</span> res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Access-Control-Allow-Headers'</span>, <span class="hljs-string">'Content-Type, Authorization'</span>); <span class="hljs-comment">// Allow specific headers</span> <span class="hljs-title function_">next</span>(); });

<span class="hljs-comment">// Your routes and other middleware</span> app.<span class="hljs-title function_">get</span>(<span class="hljs-string">'/example'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { res.<span class="hljs-title function_">send</span>(<span class="hljs-string">'Hello from example route!'</span>); });

<span class="hljs-comment">// Start the server</span> app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>, <span class="hljs-function">() =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Server is running on port 3000'</span>); });</pre></div><div id="380c" class="link-block"> <a href="https://expressjs.com/en/resources/middleware/cors.html"> <div> <div> <h2>cors</h2> <div><h3>CORS is a node.js package for providing a Connect/ Express middleware that can be used to enable CORS with various…</h3></div> <div><p>expressjs.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*nxnn9Nl6WT84v-bl)"></div> </div> </div> </a> </div><p id="0de6"><b>2. APACHECONF</b></p><p id="1e2a"><code>Example conf</code> file like (<code>httpd.conf</code> and <code>apache.conf</code>), or in an <code>.htaccess</code> file</p><p id="ee88"><a href="https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header">https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header</a></p><div id="f036"><pre>Header <span class="hljs-built_in">set</span> Access-Control-Allow-Origin <span class="hljs-string">'https://test.com'</span></pre></div><div id="f412" class="link-block"> <a href="https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header"> <div> <div> <h2>mod_headers - Apache HTTP Server Version 2.4</h2> <div><h3>This module provides directives to control and modify HTTP request and response headers. Headers can be merged…</h3></div> <div><p>httpd.apache.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*SzsHKCFc5Qn-naU8)"></div> </div> </div> </a> </div><p id="ea60"><b>3. NGINX</b></p><div id="2a88"><pre>add_header <span class="hljs-symbol">'Access</span>-Control-Allow-Origin<span class="hljs-string">' '</span>

Options

https:<span class="hljs-comment">//test.com' always;</span></pre></div><div id="f84e" class="link-block"> <a href="https://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header"> <div> <div> <h2>Module ngx_http_headers_module</h2> <div><h3>The ngx_http_headers_module module allows adding the "Expires" and "Cache-Control" header fields, and arbitrary fields…</h3></div> <div><p>nginx.org</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div><figure id="b47b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lcHFl4VK-VoUeW6O0qTvLg.png"><figcaption></figcaption></figure><h1 id="7e71">Tomorrow we will learn about CORS Preflight Request Failure</h1><h1 id="0a20">Happy Coding and Stay Tuned :)</h1><p id="fa23" type="7">Kind is always cool !!!</p><p id="1969" type="7">Share knowledge to gain knowledge !!!!</p><p id="aea5" type="7">Be kind and treat people with respect !</p><h1 id="cf32">If you find my blog helpful, then please subscribe, claps and follow to support :)</h1><div id="c9a4" class="link-block"> <a href="https://kirtikau.medium.com/javascript-day-34-mastering-javascript-basics-a-comprehensive-guide-for-interview-preparation-96181febaa0a"> <div> <div> <h2>JavaScript Day 34 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation</h2> <div><h3>100 Days of JavaScript Interview Prep: A Beginner’s Journey</h3></div> <div><p>kirtikau.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*8aLCtBeTmiwar2o11vM3Eg.png)"></div> </div> </div> </a> </div><div id="c2cc" class="link-block"> <a href="https://kirtikau.medium.com/list/6d895127c989"> <div> <div> <h2>100 Days of JavaScript Interview Prep: A Beginner’s Journey</h2> <div><h3>Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation (00 Days of JavaScript Interview Prep: A…</h3></div> <div><p>kirtikau.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*d8b12a16b592235c56284cb5a2933b01f08a9ecf.jpeg)"></div> </div> </div> </a> </div><div id="a8b2" class="link-block"> <a href="https://rohitsportsphysiorehabclinic.co.in/?source=post_page-----96181febaa0a--------------------------------"> <div> <div> <h2>Home - Krishna Sports Injuries Physiotherapy & Rehab Clinic</h2> <div><h3>Krishna Sports Injuries Physiotherapy & Rehab Clinic There are plenty ways how to make an appointment. You can call us…</h3></div> <div><p>rohitsportsphysiorehabclinic.co.in</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*zcYbJdhaWMomd1P5)"></div> </div> </div> </a> </div><div id="e1bc" class="link-block"> <a href="https://kirtikau.medium.com/list/953da44e71ce"> <div> <div> <h2>Explore OpenAI, ChatGPT , Next.js, the React framework</h2> <div><h3>Explore OpenAI, ChatGPT , Next.js, the React framework that empowers developers with server-side rendering, static site…</h3></div> <div><p>kirtikau.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*2ad63dbb6593f826f599de4c13654700cb4eb24e.jpeg)"></div> </div> </div> </a> </div></article></body>

JavaScript Day 35 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation

100 Days of JavaScript Interview Prep: A Beginner’s Journey

JavaScript Day 35 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation

Understanding the CORS POLICY and ERRORS

Welcome to Day 35–100 Days of JavaScript Interview Prep: A Beginner’s Journey with understanding the CORS Errors.

What do you understand by CORS Errors and what kind of errors ?

Answer

CORS (Cross-Origin Resource Sharing) errors occur when a web application hosted on one domain tries to access resources from another domain.

It is common error when we develop and host any application

99.9% developer usually faced these errors when web application hosted on one domain which tries to access resources from another domain.

Even we can easily reproduce it on localhost application.

Example —

When we’re developing locally, we might have different parts of your application running on different ports, like your frontend on one port and your backend on another.

This is a common use -case with every developer.

WHY CORS are Important

  1. CORS is important because it allows browsers to enforce the same-origin policy(SOP)
  2. CORS safeguard the integrity of a webpage and privacy of data.
  3. It save a website from malicious threats.
  4. It is the HTTP header based mechanism.

It is a security mechanism implemented by web browsers to prevent malicious scripts from making unauthorized requests to other domains.

What is Same-origin policy ?

It is a security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin.

Simple words -

The rules is keep your things safe and prevent strangers from messing with your things in your boundaries.

In the world of the internet, websites also have rules like this, called the Same-Origin Policy (SOP).

  1. It helps keep your browsing experience safe.
  2. It stops malicious threats from one website from sneaking into other websites.

What are the common errors of CORS ?

Some common causes of CORS errors and how to address them:

Today we will discuss the Missing or Incorrect CORS Headers in detail

Missing or Incorrect CORS Headers:

Errors Examples as below  
 
CORS issues due to missing headers in preflight response 
CORS header 'Access-Control-Allow-Origin' missing
“no ‘access-control-allow-origin’ header is 
 present on the requested resource”
Reason: CORS header 'Access-Control-Allow-Origin' missing

ROOT Cause Analysis (RCA)

It indicates the server which we are trying to access is missing the necessary CORS headers in its response. It’s not including the Access-Control-Allow-Origin header, which tells the browser which origins are allowed to access the resource.

Solution

Ensure that the server is configured to include the proper CORS headers, such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, etc.

To fix this issue, we will need to update the server configuration to include the Access-Control-Allow-Origin header in its responses.

Examples

How to fix it

  1. With Express.js Example
// Assuming you're using Express.js for your server

const express = require('express');
const app = express();

// Add CORS middleware
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); // Allow requests from any origin
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // Allow specific HTTP methods
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Allow specific headers
  next();
});

// Your routes and other middleware
app.get('/example', (req, res) => {
  res.send('Hello from example route!');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

2. APACHECONF

Example conf file like (httpd.conf and apache.conf), or in an .htaccess file

https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header

Header set Access-Control-Allow-Origin 'https://test.com'

3. NGINX

add_header 'Access-Control-Allow-Origin' 'https://test.com' always;

Tomorrow we will learn about CORS Preflight Request Failure

Happy Coding and Stay Tuned :)

Kind is always cool !!!

Share knowledge to gain knowledge !!!!

Be kind and treat people with respect !

If you find my blog helpful, then please subscribe, claps and follow to support :)

Coding
Javascript Tips
Front End Development
Coding Interviews
Programming
Recommended from ReadMedium