I'm trying to use W3C's CSS Validator Web Service API in a Chrome new tab extension. The docs claim that a request is a simple HTTP GET call to a URI, so I figured this should work:
fetch('http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json')
.then((response) => {
// do stuff with response
});
Unfortunately the promise fails and I get a message like:
Failed to load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.
How am I supposed to make a "simple" GET
request if the resource doesn't allow CORS
?
Thanks!
2017-10-22 Update: The change for adding CORS support to the CSS Validator was merged and pushed to production, so the following now works as-is:
const validatorURL = 'https://jigsaw.w3.org/css-validator/validator' +
'?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json';
fetch(validatorURL)
.then(response => response.json())
.then(results => console.log(results))
Original answer:
The CSS Validator doesn’t send the necessary CORS response headers. To fix that, I’ve raised a pull request with a change against the CSS Validator sources that’ll enable your code snippet to work as-is. I’ll post an update here once the change is merged and pushed to production.
In the meantime, you can work around the issue by making your request through a CORS proxy:
const proxyURL = 'https://cors-anywhere.herokuapp.com/';
const validatorURL = 'http://jigsaw.w3.org/css-validator/validator' +
'?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json';
fetch(proxyURL + validatorURL)
.then(response => response.json())
.then(results => console.log(results))
For details abou why that works, see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API.