简体   繁体   中英

Making request to remote server from localhost getting preflight Request 'Access-Control-Allow-Origin'

Complete error is this:

XMLHttpRequest cannot load http://ip:port/path . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access.

Environment Details:

Exhausted tried almost everything, but can't accomplish task.

Actually I am requesting node.js server, from angular js client. I have tried all possible options.

Flow is in this way:

  1. Request initiated from web portal designed in angular js.
  2. Hit node.js server on remote machine.

What I have tried so for

expressjs/cors and Solving "Access-Control-Allow-Origin" in localhost NodeJS + Express

Client End Code


$scope.testFunc = function () {
    $("div#preloader").show();
    $http.post(rtcControlUrl, data).success(function () {
        $("div#preloader").hide();
        if(response.success)
            $.notify(response.msg, "success");
        else $.notify(response.msg);
        console.log(response.data);
    }).error(function () {
        $.notify("Request timeout!");
        $("div#preloader").hide();
    });
};

app.post("/path", cors(), function(req, res) {
           shelljs.exec("bash test.sh",{silent:true,async:false}).output;
                    console.log(output);
                    res.json({"success": true, msg: 'some text', 'data' : output});
            }
    });

The error message says Response to preflight request .

If you look up preflight request you will see that is uses the OPTIONS method.

"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain

Your code:

app.post("/path", cors()

… only uses the cors middleware on POST requests.

You need to handle the OPTIONS request too.

I fix this issue by using NPM Request Module with request header

{
   name : 'content-type',
   value: 'application/x-www-form-urlencoded'
}

Now I resolved this issue without setting any header on server end code. I achieved this in three steps.

Client

$scope.testFunction= function () {
        $("div#preloader").show();
        $http.get(url).success(function (response) {
            $("div#preloader").hide();
            if(response.success)
                $.notify(response.msg, "success");
            else $.notify(response.msg);
            console.log(response.data);
        }).error(function () {
            $.notify("Request timeout!");
            $("div#preloader").hide();
        });
    };

Local node server

request({
        url    : url,
        method : "POST",
        json   : true,
        headers: [
            {
                name : 'content-type',
                value: 'application/x-www-form-urlencoded'
            }
        ],
        body   : data
    }, function optionalCallback(err, response) {
        if (err) {
            console.error('**************[page][functionName][Request][Fail]*****************', err);
            res.json({success: false, msg: 'msg', data: err});
        } else {
            var dataObj = (response && response.body) ? response.body.data : undefined;
            console.info('*************************[pageName][functionName][Request][Success]**********************');
            res.json({success: true, msg: 'msg', data: ''});
        }
    });

Remember on local node server headers in same way as described in this video

End server upon which I am executing final business logic.

var cors = require('cors');
app.options('*', cors());
app.post("/path", cors(), function(req, res) {
           shelljs.exec("bash test.sh",{silent:true,async:false}).output;
                    console.log(output);
                    res.json({"success": true, msg: 'some text', 'data' : output});
            }
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM