如何调试“请求的资源上不存在‘Access-Control-Allow-Origin’标头" [英] How to debug "No 'Access-Control-Allow-Origin' header is present on the requested resource"
问题描述
我在浏览器控制台上显示此错误:
<块引用>XMLHttpRequest 无法加载
您需要在您的 Web 服务器上启用 CORS(跨源资源共享).请参考此资源.
您需要将响应标头设置为:
Access-Control-Allow-Origin:*
此链接包含设置 CORS 所需的所有信息
为所有域启用 CORS 不是一个好的做法,因此您应该在一切正常运行时限制它.
另一种解决方法是为 curl 请求使用单独的 API
在您自己的 API 中调用 URL 并使用您的服务器端通过 cURL 或其他方式访问数据.我有一个当前情况相同的工作项目(Laravel + AngularJs).
我使用 cURL 请求进行远程身份验证检查的示例代码.
代码为 Laravel-PHP 格式,希望你能转换成你正在使用的语言.
请求函数:
公共函数 curlRequester($url,$fields){//打开连接$ch = curl_init();//设置 url、POST 变量的数量、POST 数据curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);//执行帖子$result = curl_exec($ch);//关闭连接curl_close($ch);$result_json_decoded = json_decode($result, true);返回 $result_json_decoded;}
控制器功能
公共函数login(){//设置POST参数$fields = 数组('用户名' =>输入::get('用户名'),'密码' =>输入::get('密码'));$url = 'http://www.this-is-api-url.com/login';$result = $this->curl->curlRequester($url,$fields);返回响应()-> json($result);}
角度请求函数
$scope.authCheck = function(){$http({url:'http://www.our-project-url/login',方法:发布",数据:{用户名":rameez",密码":rameezrami"}}).成功(功能(响应){如果(响应.状态== 1){$location.path("/主页");}else if(response.status==0){$scope.login_error_message_box = true;$scope.login_error_message_text =response.message;}});}
I am getting this error shown on browser console:
XMLHttpRequest cannot load http://localhost:8080/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9009' is therefore not allowed access.
The environment I am using are:
- Backend- Spring Boot
- Front End- Angularjs
- Web Server- Grunt
On server, I am already defining headers in request and response as:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");
if (httpRequest.getMethod().equals("OPTIONS")) {
httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
return;
}
}
I already found this question on this link No 'Access-Control-Allow-Origin' header is present on the requested resource but couldn't find the appropriate solution.
Here is the browser network image:
You need to enable CORS(Cross Origin Resource Sharing) on your web server. Please refer to this resource.
You need to set your response header to:
Access-Control-Allow-Origin: *
This link has all the info needed to set CORS
Enabling CORS for all domain is not a good practice, so you should restrict it when everything is up and running.
Another workaround is to have a separate API for curl request
Call a URL in your own API and access the data using your server side with cURL or something. I have a current working project with same situation (Laravel + AngularJs).
My sample code for the remote auth check with cURL request.
Code is in Laravel-PHP format, I hope you can convert to the language you are working on.
Requester function:
public function curlRequester($url,$fields)
{
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
$result_json_decoded = json_decode($result, true);
return $result_json_decoded;
}
Controller function
public function login()
{
// set POST params
$fields = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$url = 'http://www.this-is-api-url.com/login';
$result = $this->curl->curlRequester($url,$fields);
return response()->json($result);
}
Angular request function
$scope.authCheck = function(){
$http({
url:'http://www.our-project-url/login',
method:"post",
data:{"username": "rameez", "password":"rameezrami"}
})
.success(function(response) {
if(response.status==1){
$location.path("/homepage");
}else if(response.status==0){
$scope.login_error_message_box = true;
$scope.login_error_message_text =response.message;
}
});
}
这篇关于如何调试“请求的资源上不存在‘Access-Control-Allow-Origin’标头"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!