问题
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