Search code examples
angularjsajaxrestcorszingchart

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response


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


Solution

  • 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.