DEV Community

Jason Reed
Jason Reed

Posted on

CORS Problem Workaround for Consuming DEV.TO API on Your Website

Ok recently while updating my website to pull my blog posts from DEV.TO instead of WordPress I kept getting a CORS failure in my browser. So I started investigating and found that DEV.TO's TLS Certificate is malformed, in that it is not issued to DEV.TO but to the server on which DEV.TO runs. This is enough to prevent a browser from accessing when making asynchronous calls. Now I've already asked about this problem, and I've been informed that it is on the "TODO" list. Since the API is still in beta, I figure it's not too urgent. Yet I still wanted to have my posts displaying on my website! So how did I get around the CORS protection of my browser? Simple, I built a small PHP script that when called makes a call to the DEV.TO API, and the returns the result with the correct headers. Since it is located on my website's server, CORS is not a problem.

To help others I've provided the PHP script below, all you need to do is modify the URL portion to the correct DEV.TO API endpoint.

<?php

header('Content-Type: application/json; charset=utf-8');

$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, "https://dev.to/api/__ENDPOINT__");
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curlHandle);
curl_close($curlHandle);

echo $result;

?>

Top comments (0)