DEV Community

Cover image for How to Fix CORS Origin Error in Javascript
Stephen Michael
Stephen Michael

Posted on • Originally published at axxellanceblog.com

How to Fix CORS Origin Error in Javascript

Introduction

Cross-Origin Resource Sharing (CORS) is a security mechanism implemented in web browsers to restrict resource sharing between different domains. While CORS plays an essential role in web security, it can also cause problems when you're trying to access resources from a different domain through JavaScript.

Original source of this article can be found in Axxellanceblog

If you're a developer working with JavaScript, you've likely encountered a CORS Origin error, which can be frustrating and time-consuming to fix. In this blog post, we'll explore what CORS is, why it's important, and how to fix the CORS Origin error in JavaScript. Whether you're a seasoned developer or just starting with JavaScript, this guide will help you understand CORS and provide you with actionable steps to resolve the CORS Origin error in your projects. So, let's dive in!

This is an example of a CORS error:

0*b I2yx Kryq Jzy Ukud

What is CORS

Cross-Origin Resource Sharing (CORS) is a security feature implemented in web browsers to protect against cross-site attacks by restricting resource sharing between different domains. In this blog post, we'll explore what CORS is and why it's important to understand, especially for web developers.

CORS works by enforcing the "same-origin” policy, which means that a web page can only access resources from the same domain as the page itself. This policy is in place to prevent malicious scripts on one site from accessing resources on another site. However, there are legitimate reasons why a web application may need to access resources from a different domain. In such cases, CORS allows a server to explicitly grant access to resources from a different domain.

CORS is crucial for web security as it prevents unauthorized access to sensitive data, such as user credentials or payment information. It also ensures that a web application can only access the resources it needs, preventing malicious scripts from accessing unnecessary resources.

In summary, CORS is a security feature that restricts resource sharing between different domains, enforcing the same-origin policy. It's essential to understand how CORS works and how to use it properly, especially if you're a web developer. By following best practices and understanding the importance of web security, you can ensure that your web applications are safe and reliable for users to interact with.

3 Ways to Fix The CORS Error in Web Browser

You will learn three effective ways to fix the CORS origin error in JavaScript. When you encounter a CORS origin error, it can be frustrating and time-consuming to resolve. However, by following the three methods we will discuss, you can easily fix the issue and ensure that your web application is secure and functional.

Fixed one: Installing a browser extension

You can successfully bypass the CORS origin error locally by installing an extension on your local browser called the Moesif CORS extension. Installing the Moesif CORS extension is the quickest solution. Clicking it in your browser after installation will enable the extension. Ensure that the label of the icon changes from "off" to "on.” Then refresh your application, and your API requests should now work🎉.

Yet, the plugin fix is misleading.

Why!!! you might ask, Well, the plugin undoubtedly resolves the problem. The only machine that this fix works on is your own. It's okay to have a plugin installed that can assist you in getting around the problem when working on local development.

Nevertheless, you cannot anticipate that your users will also install the plugin when you publish your application. It wouldn't be a smart business move…

There must be better options available. In order to get there, let's check out the next two fixes.

Fixed two: Send your request to a proxy

You cannot demand that your users install a plugin that applies a header in the front end in order to trick their browsers. Yet, you have control over the backend URL that receives API queries from web applications.

The cors-anywhere server acts as a proxy, inserting CORS headers into requests. A proxy serves as a mediator between a client and a server. The Cors-Anywhere proxy server functions here as a middleman between the frontend web app making the request and the server providing the data. Similar to the Allow-control-allow-origin plugin, it adds the more open Access-Control-Allow-Origin: * header to the response.

It works like this. Say your frontend is trying to make a GET request to:

https://joke-api-strict-cors.appspot.com/jokes/random

But there is no Access-Control-Allow-Origin value set for this API that would allow the web application domain to access it. So instead, send your GET request to:

https://cors-anywhere.herokuapp.com/<https://joke-api-strict-cors.appspot.com/jokes/random>

The proxy server receives the https://joke-api-strict-cors.appspot.com/jokes/random from the URL above. Then it sends a request to that server to obtain a response. Finally, the proxy updates the original response with the Access-Control-Allow-Origin: * header.

The fact that this solution functions in both development and production makes it fantastic. In conclusion, you are profiting from the fact that browser-to-server communication is the only scenario in which the same origin policy is used. Thus, it need not be imposed on server-to-server communication!

The Cors-Anywhere proxy's one drawback is that it can frequently take a while to get a response. Your applications might appear to be running a little slowly because of the high latency.

This brings us to a final, even better approach.

Fixed three: Build your own proxy

The solution I suggest in cases like these is to create your own proxy! Like the last technique, you make use of the fact that server-to-server communication does not enforce the same origin policy. You also take care of the latency issue. You can allocate as many resources as you need to your own servers and are not required to share the CORS-anywhere proxy with other users.

Here is some simple Node.js code that builds a proxy server for the same https://joke-api-strict-cors.appspot.com/ from above using the express web framework:

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

const app = express();
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/jokes/random', (req, res) => {
  request(
    { url: '<https://joke-api-strict-cors.appspot.com/jokes/random>' },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Enter fullscreen mode Exit fullscreen mode

How does that function? Every response from the server receives an Access-Control-Allow-Origin: * header thanks to the proxy's use of express middleware. The proxy requests a random joke from another server at its own jokes/random HTTP endpoint. The request is not blocked by the same-origin policy despite the fact that the domains are distinct. This is a server-to-server request, after all. The resultant data and the Access-Control-Allow-Origin: * header are then created by the proxy and sent back to the original requester (a browser app).

Conclusion

In conclusion, the CORS Origin error in JavaScript can be a challenging issue to deal with, but understanding what CORS is and how it works can help you overcome it. By implementing the steps we've discussed in this post, you can fix the error and ensure that your website or application is secure and functional. Remember to always consider security when sharing resources between domains, as this is crucial to maintaining a safe and reliable web environment.

We hope this guide has been helpful in giving you an overview of CORS and how to fix the CORS Origin error in JavaScript. By following these best practices, you can enhance your development skills and create robust web applications that work seamlessly across different domains.

As you continue to work with JavaScript, keep in mind that there are many other potential issues you may encounter. However, with a solid understanding of web development principles and best practices, you can overcome any obstacle and create amazing web applications that m

Follow ME

Hey there! If you're interested in tech or programming articles, you should definitely give me a follow on any of the social media platforms below. I regularly post articles related to tech and programming, and I share valuable resources and insights. Plus, by following me, you'll be able to stay up to date on all the latest and greatest in the world of tech and programming. So, what do you say? Will you give me a follow?

Follow me on Dev.to, Twitter, LinkedIn, GitHub, Medium, Facebook, and my blog's Facebook page.

Top comments (5)

Collapse
 
ravavyr profile image
Ravavyr

Could you NOT teach people fix #1 ?
That's not a fix, it's a lie, it makes devs think their code works until it gets deployed and then their code will break again on the same thing, but in production.

2 and 3 are not explained right either. You don't setup "Proxies" to fix CORS.
This is not "fixing it".

To really fix CORS the endpoint has to set a header that allows Cross-Origin-Request-Sharing which means it allows browsers and other domains to send requests to that endpoint/url/api/whateveryoucallit.

Literally this piece of code is the ONLY CORRECT WAY OF SOLVING CORS ERRORS
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});

[disclaimer: this example [like every other newbie example] is using Node.
Apache, NginX, IIS etc, have other ways of setting this header as do other backend languages like PHP, Python etc]

Instead of a * the dev can set specific domains like bob.com or localhost or an ip address and comma-separate multiple domains so they can allow their local environment and the prod environment to send requests to that endpoint.

THAT IS IT....the rest is nonsense and people need to stop teaching it because it's literally driving me up a wall every time i have to explain to someone that "bypassing this error is NOT the same as FIXING THIS ERROR".

/End rant.

Collapse
 
mc-stephen profile image
Stephen Michael • Edited

Well the article said 3 fixed and the same article really did say that the first one is actually not a fix and that the 3rd fix is actually the recommended fix, so it still looks good to me. Thanks for your intake anyways.

Collapse
 
getwidget profile image
GetWidget

CORS (Cross-Origin Resource Sharing) is a security mechanism used by web browsers to prevent web pages from making requests to a different domain than the one that served the original page. If you are trying to make an AJAX request to a different domain using JavaScript, you may encounter a CORS origin error.

Here are some steps you can take to fix the CORS origin error in JavaScript:

Enable CORS on the server-side: To enable CORS on the server-side, you need to set the Access-Control-Allow-Origin header in the response to the domain or domains you want to allow. For example, if you want to allow all domains, you can set it to "*".

Use a proxy server: You can use a proxy server to bypass the CORS origin error. The proxy server acts as an intermediary between your JavaScript code and the server you want to make a request to.

Use JSONP (JSON with Padding): JSONP is a technique that allows you to make cross-domain requests by loading a script from a different domain that returns JSON data. This technique works by adding a callback function to the request URL, which the server calls with the JSON data.

Use a browser extension: There are browser extensions that can disable the CORS origin policy in your browser, allowing you to make cross-domain requests. However, this is not recommended as it can compromise the security of your browser.

In summary, to fix the CORS origin error in JavaScript, you can enable CORS on the server-side, use a proxy server, use JSONP, or use a browser extension.

Collapse
 
lexlohr profile image
Alex Lohr

And the actual fix: use a simple request in order not to trigger cross-origin request security at all.

Collapse
 
rvandervelde profile image
Remco van der Velde

If you want to use a session then cors cannot be a wildcard, also fixing cors is the way to go, not around it