Reputation: 1099
I have the following code which worked 6 days ago:
function showProduct(barcode) {
let url = "https://api.barcodelookup.com/v2/products?barcode=" + barcode + "&key=mj1pm32ylcctxj1byaiaxxxxxxxxxx";
const options = { method: 'GET' };
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
setTimeout(function(){
if (myJson == undefined)
{
console.log("fetch failed")
}
else
{
//inspect the data that the WebAPI returned
console.log("myJson: ", myJson);
console.log(myJson.products[0].barcode_formats);
Quagga.stop();
}
}, 3000);
});
}
and the value being passed into the function is 5000159459228. When I executed this code last week, I was receiving a response back from the API and I was able to pick up the individual fields being returned.
Today, I started debugging a different feature of my app and now I receive this error when executing the above listed code:
Failed to load https://api.barcodelookup.com/v2/products?barcode=5000159459228&key=mj1pm32ylcctxj1byaiaxxxxxxxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
followed by this error:
Uncaught (in promise) TypeError: Failed to fetch
and then this:
newscan:91 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.barcodelookup.com/v2/products?barcode=5000159459228&key=mj1pm32ylcctxj1byaiaxxxxxxxxxx with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
If I manually paste the string that I build into the url variable into a browser, I do get a valid response back.
Any suggestions?
Upvotes: 2
Views: 1872
Reputation: 21357
Jonathan what you have there is a cors
problem. A quick way to solve that if you are using express in your backend is just add CORS module with npm i --save cors
and then use it as a middleware:
const cors = require('cors');
app.use(cors());
You can always add the headers yourself. Take a deepr look at Enable CORS.org
Your question was also answered here: [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
Upvotes: 1