skip to Main Content

I have this medium API Request Data. Medium Docs

Example request:

GET /v1/me HTTP/1.1
Host: api.medium.com
Authorization: Bearer 181d415f34379af07b2c11d144dfbe35d
Content-Type: application/json
Accept: application/json
Accept-Charset: utf-8

In php CODE SAMPLE below, Everything is working fine as I can get my data successfully from Medium API

$url ="https://api.medium.com/v1/me";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization: Bearer 29f812842-xxxxxxxxxxx'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $output = curl_exec($ch);

Here is my Issue. When I tried to fetch the data from javascript it throw error below

XHROPTIONS
https://api.medium.com/v1/me
CORS Missing Allow Origin

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.medium.com/v1/me. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.

below is the code causing the error

async function GetUsersData() {

    try {                
const response = await fetch('https://api.medium.com/v1/me', {
    method: 'GET',
    mode: 'cors',
    credentials: 'include',
    headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer  29f8128xxxx'
  }
});

console.log(response);
alert(response);

} catch (error) {
    // handle the error
alert(error);
} 

}
GetUsersData();

3

Answers


  1. It seems like you are adding the proper header into your request which is required by he Medium API. We need to the proper Access-Control-Allow-Origin into your header which is allowed by Medium API. As, we do not control Medium API Code. There are few work around to this. One way is to make our own Server Side Proxy. You can try to use Node JS or any other Server Side language for this particular use case and then call that end point from your client side application.

    We can control our own Server Side CORS. Please do try this approach and let me know if you still face the issue. Share detail log of it.

    Login or Signup to reply.
  2. I feel the browser is enforcing the Same-Origin Policy, which prevents making requests to a different domain unless the target server explicitly allows it by including specific CORS headers in the response.

    I would suggest you use a server-side script to fetch the data from the Medium API. This way, your JavaScript can communicate with your server (which is same-origin) and your server can then communicate with the Medium API.

    For example:

    // Node.js Server-Side Code
    
    const express = require('express');
    const fetch = require('node-fetch');
    const app = express();
    
    app.get('/medium-data', async (req, res) => {
      const url = 'https://api.medium.com/v1/me';
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer 29f8128xxxx'
        }
      });
      const data = await response.json();
      res.json(data);
    });
    
    app.listen(3000, () => {
      console.log('Server running on port 3000');
    });
    
    
    
    
    // Client-Side JavaScript
        async function GetUsersData() {
     try {                
        const response = await fetch('http://localhost:3000/medium-data');
        const data = await response.json();
        console.log(data);
        alert(JSON.stringify(data));
      } catch (error) {
        alert(error);
      }
    }
    
    GetUsersData();
    
    Login or Signup to reply.
  3. To work around this issue, you can use a server-side proxy to handle the API request. This way, the request is made server-to-server, bypassing the CORS restrictions in the browser.

    Using a Server-Side Proxy
    Set Up a Proxy Server

    Here’s an example using Node.js and Express:

    // server.js
    const express = require('express');
    const fetch = require('node-fetch');
    const app = express();
    
    app.get('/api/medium/me', async (req, res) => {
      try {
        const response = await fetch('https://api.medium.com/v1/me', {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer 29f812842-xxxxxxxxxxx'
          }
        });
        const data = await response.json();
        res.json(data);
      } catch (error) {
        res.status(500).send(error.toString());
      }
    });
    
    app.listen(3000, () => console.log('Server running on port 3000'));
    

    Update Your Frontend Code
    Modify your JavaScript to make a request to your proxy server instead:

    async function GetUsersData() {
        try {
            const response = await fetch('/api/medium/me');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            console.log(data);
            alert(JSON.stringify(data));
        } catch (error) {
            alert('Error: ' + error.message);
        }
    }
    GetUsersData();
    

    Using a CORS Proxy (Temporary Solution)
    If you need a quick solution and are okay with potential security and reliability issues, you can use a CORS proxy service like cors-anywhere:

    async function GetUsersData() {
        try {
            const response = await fetch('https://cors-anywhere.herokuapp.com/https://api.medium.com/v1/me', {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer 29f812842-xxxxxxxxxxx'
                }
            });
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            console.log(data);
            alert(JSON.stringify(data));
        } catch (error) {
            alert('Error: ' + error.message);
        }
    }
    GetUsersData();
    

    For a robust and secure solution, setting up a server-side proxy is recommended. The CORS proxy can be used for quick testing but is not ideal for production environments.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search