“No 'Access-Control-Allow-Origin' header present on requested origin” error for res.redirect(“http://www.google.com”)

别等时光非礼了梦想. 提交于 2020-01-17 05:37:47

问题


I have a simple task on cross origin domain request.So i created a sample express application that have a route to '/redirect', this will redirect to "http://www.google.com". On front end i created a button that have a onclick event , this will request the '/redirect' .

Code i have on server side:

app.get('/redirect',function(req,res){
  res.redirect("http://www.google.com");
})

on front end :

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script type="text/javascript">
      var app = angular.module('myApp',[]);
      app.controller('crtl',function ($scope,$http,$timeout){
        $scope.fun1 = function(){
          $http({
            method: 'GET',
            url: '/redirect'
          }).then(function successCallback(response) {
               // console.log(response.data)
               console.log("got the request for redirect");
            }, function errorCallback(response) {});
        }
      });
    </script>
  </head>
  <body ng-app="myApp" ng-controller="crtl">
    <center><br/>
      <button ng-click="fun1()" class="btn">Click Me</button>
    </center>
  </body>
</html>

回答1:


You can't use your server to enable direct cross domain access to another domain. The browser simply doesn't work that way. The browser requires the domain that you are trying to access (www.google.com in your example) to be the one that enables cross domain access.

res.redirect() just tells the browser to fetch content from a different source. If the browser doesn't have the cross origin rights to fetch that content, then res.redirect() won't work any better than the browser trying to access it directly.

You could embed the cross origin content in its own iframe and the content could be displayed there, but you wouldn't be allowed access the content from your own Javascript (for the same cross origin reasons).

You could proxy the content from your server which means you could ask your server to get the content for you and your server would fetch it and return it to the browser (via your domain). This works for some uses, but it depends upon what you're trying to do with the content (something you don't share in your question) whether this would satisfy your needs.



来源:https://stackoverflow.com/questions/40080572/no-access-control-allow-origin-header-present-on-requested-origin-error-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!