Access-Control-Allow-Origin and Angular.js $http

前端 未结 7 1797
盖世英雄少女心
盖世英雄少女心 2020-12-24 06:37

Whenever I make a webapp and I get a CORS problem, I start making coffee. After screwing with it for a while I manage to get it working but this time it\'s not and I need he

相关标签:
7条回答
  • 2020-12-24 06:38

    Adding below to server.js resolved mine

        server.post('/your-rest-endpt/*', function(req,res){
        console.log('');
        console.log('req.url: '+req.url);
        console.log('req.headers: ');   
        console.dir(req.headers);
        console.log('req.body: ');
        console.dir(req.body);  
    
        var options = {
            host: 'restAPI-IP' + ':' + '8080'
    
            , protocol: 'http'
            , pathname: 'your-rest-endpt/'
        };
        console.log('options: ');
        console.dir(options);   
    
        var reqUrl = url.format(options);
        console.log("Forward URL: "+reqUrl);
    
        var parsedUrl = url.parse(req.url, true);
        console.log('parsedUrl: ');
        console.dir(parsedUrl);
    
        var queryParams = parsedUrl.query;
    
        var path = parsedUrl.path;
        var substr = path.substring(path.lastIndexOf("rest/"));
        console.log('substr: ');
        console.dir(substr);
    
        reqUrl += substr;
        console.log("Final Forward URL: "+reqUrl);
    
        var newHeaders = {
        };
    
        //Deep-copy it, clone it, but not point to me in shallow way...
        for (var headerKey in req.headers) {
            newHeaders[headerKey] = req.headers[headerKey];
        };
    
        var newBody = (req.body == null || req.body == undefined ? {} : req.body);
    
        if (newHeaders['Content-type'] == null
                || newHeaders['Content-type'] == undefined) {
            newHeaders['Content-type'] = 'application/json';
            newBody = JSON.stringify(newBody);
        }
    
        var requestOptions = {
            headers: {
                'Content-type': 'application/json'
            }
            ,body: newBody
            ,method: 'POST'
        };
    
        console.log("server.js : routes to URL : "+ reqUrl);
    
        request(reqUrl, requestOptions, function(error, response, body){
            if(error) {
                console.log('The error from Tomcat is --> ' + error.toString());
                console.dir(error);
                //return false;
            }
    
            if (response.statusCode != null 
                    && response.statusCode != undefined
                    && response.headers != null
                    && response.headers != undefined) {
                res.writeHead(response.statusCode, response.headers);
            } else {
                //404 Not Found
                res.writeHead(404);         
            }
            if (body != null
                    && body != undefined) {
    
                res.write(body);            
            }
            res.end();
        });
    });
    
    0 讨论(0)
  • 2020-12-24 06:41

    I have found a way to use JSONP method in $http directly and with support of params in the config object:

    params = {
      'a': b,
      'callback': 'JSON_CALLBACK'
    };
    
    $http({
      url: url,
      method: 'JSONP',
      params: params
    })
    
    0 讨论(0)
  • 2020-12-24 06:46

    I'm new to AngularJS and I came across this CORS problem, almost lost my mind! Luckily i found a way to fix this. So here it goes....

    My problem was, when I use AngularJS $resource in sending API requests I'm getting this error message XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Yup, I already added callback="JSON_CALLBACK" and it didn't work.

    What I did to fix it the problem, instead of using GET method or resorting to $http.get, I've used JSONP. Just replace GET method with JSONP and change the api response format to JSONP as well.

        myApp.factory('myFactory', ['$resource', function($resource) {
    
               return $resource( 'http://website.com/api/:apiMethod',
                            { callback: "JSON_CALLBACK", format:'jsonp' }, 
                            { 
                                method1: { 
                                    method: 'JSONP', 
                                    params: { 
                                                apiMethod: 'hello world'
                                            } 
                                },
                                method2: { 
                                    method: 'JSONP', 
                                    params: { 
                                                apiMethod: 'hey ho!'
                                            } 
                                }
                } );
    
        }]);
    

    I hope someone find this helpful. :)

    0 讨论(0)
  • 2020-12-24 06:52

    Writing this middleware might help !

    app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,     Content-Type, Accept");
    next();
    });
    

    for details visit http://enable-cors.org/server_expressjs.html

    0 讨论(0)
  • 2020-12-24 06:56

    I've had success with express and editing the res.header. Mine matches yours pretty closely but I have a different Allow-Headers as noted below:

    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    

    I'm also using Angular and Node/Express, but I don't have the headers called out in the Angular code only the node/express

    0 讨论(0)
  • 2020-12-24 06:57

    @Swapnil Niwane

    I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

    $.ajax({
              method: 'GET',
              url: url,
              defaultHeaders: {
                  'Content-Type': 'application/json',
                  "Access-Control-Allow-Origin": "*",
                  'Accept': 'application/json'
               },
    
              dataType: 'jsonp',
    
              success: function (response) {
                console.log("success ");
                console.log(response);
              },
              error: function (xhr) {
                console.log("error ");
                console.log(xhr);
              }
    });
    
    0 讨论(0)
提交回复
热议问题