Hacking It Out: When CORS won’t let you be great

But CORS didn’t count on meeting you

Shalvah
Shalvah
Aug 21, 2017 · 5 min read

The Scenario

Image for post
Image for post
Because I had to put a pic :(

The Problem

let loadPosts = function () {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
let response = JSON.parse(this.responseText);
renderPosts(response); }
}
xhr.open("GET", "https://maximum.blog/@shalvah/posts");
xhr.setRequestHeader("Accept", 'application/json');
xhr.send();
}
Image for post
Image for post

Debugging

The Solution

xhr.setRequestHeader("Origin", 'maximum.blog');
Image for post
Image for post
xhr.open("GET", "https://cors-anywhere.herokuapp.com/https://maximum.blog/@shalvah/posts");
xhr.open("GET", "https://cors-escape.herokuapp.com/https://maximum.blog/@shalvah/posts");
{
"status": "success",
"payload": {
...
}
}

Alternative approach

getPostData(req)
.then(body => {
console.log(body);
let options = {
uri: query.url,
headers: body.headers,
method: body.method || 'GET
};

let proxyCallback = (proxyErr, proxyRes, proxyBody) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
res.write(proxyBody);
res.end();
};
request(options, proxyCallback);
})
xhr.open("POST",
"https://localhost:2000/?url=https://maximum.blog/@shalvah/posts"); // assuming you’re hosting it locally
xhr.setRequestHeader("Content-type", 'application/json’);
let data = {
headers: {
Accept: "application/json",
Origin: "http://maximum.blog"
},
method: 'GET'
};
xhr.send(JSON.stringify(data));

Netscape

A community dedicated to those who use JavaScript every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store