I get the following error in when I try to load a my webpage: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
I have looked at other answers that respond to this issue and they indicate lack of CORS support. The confusing thing is that I have cors support! At least I think I do.
I am trying to connect Zingchart to my Angular JS front end and using an AJAX request to get data from my REST API (at localhost:3000)
Here is my AJAX call:
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "http://localhost:3000/readings",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
My REST API implementation includes the following:
// CORS Support
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
My REST API was built with the help of this tutorial: https://www.youtube.com/watch?v=OhPFgqHz68o
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");
The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin. Header type.
What is the Access-Control-Allow-Origin response header? The Access-Control-Allow-Origin header is included in the response from one website to a request originating from another website, and identifies the permitted origin of the request.
Take out the "headers"
and "dataType"
. Your request will then look like this:
$.ajax({
type: "GET",
url: "http://localhost:3000/readings",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
Your headers are triggering the preflight request.
If you're using Angular, I'd highly suggest not using jQuery for AJAX and instead use Angular's built-in $http service.
I'm on the ZingChart team. Holler if we can help with your charts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With