No ‘access-control-allow-origin’ Header Is Present on the Requested Resource—when Trying to Get Data from a Rest Api

If you have ever encountered the error message “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” while trying to get data from a REST API using JavaScript, you are not alone. This error occurs when you are trying to make a cross-origin request, but the server does not include the necessary CORS (Cross-Origin Resource Sharing) headers in its response. In this blog post, we will explore a few solutions to overcome this issue and successfully retrieve data from the REST API.

Solution 1: Proxy Server

One way to bypass the ‘Access-Control-Allow-Origin’ header issue is by using a proxy server. A proxy server acts as an intermediary between your JavaScript code and the REST API server, allowing you to make the request from the same origin. Here’s an example of how you can set up a simple proxy server using Node.js and Express:

const express = require('express');
const fetch = require('node-fetch');

const app = express();

app.get('/api/data', async (req, res) => {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.listen(3000, () => {
  console.log('Proxy server listening on port 3000');
});

In the above code snippet, we define a route ‘/api/data’ which acts as a proxy for the actual REST API endpoint. When a request is made to this route, our server makes a request to the REST API server, retrieves the data, and sends it back as a response to the client. This way, the client-side JavaScript code can make requests to the proxy server, which is considered the same origin.

Solution 2: CORS Anywhere

Another solution is to use a third-party service called CORS Anywhere. CORS Anywhere acts as a proxy server that adds the necessary CORS headers to the response, allowing you to make cross-origin requests directly from your JavaScript code. Here’s an example of how you can use CORS Anywhere to overcome the ‘Access-Control-Allow-Origin’ header issue:

const apiUrl = 'https://cors-anywhere.herokuapp.com/https://api.example.com/data';

fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    // Process the retrieved data
  })
  .catch(error => {
    console.error('Error:', error);
  });

In the above code snippet, we prepend the API URL with ‘https://cors-anywhere.herokuapp.com/’ to use CORS Anywhere as a proxy. This way, the response from the REST API server will include the necessary CORS headers, allowing the JavaScript code to access the data without any issues.

By using either a proxy server or CORS Anywhere, you can overcome the ‘Access-Control-Allow-Origin’ header issue and successfully retrieve data from a REST API using JavaScript. Choose the solution that best fits your requirements and start building amazing applications!

I hope you found this article helpful. If you have any further questions or suggestions, feel free to leave a comment below.

Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *