【发布时间】:2015-11-27 02:27:27
【问题描述】:
我目前正在为我的实时服务器部署一个基本 API,我遇到了(我认为是)CORS 问题,但发生了一些我无法解释的行为。
我正在从 AngularJS 前端与 Laravel 5 (+ laravel-cors) 后端进行通信。
我开始使用一个简单的 jQuery AJAX 调用(如下)进行测试,当我从本地 Vagrant 环境 (http://dev.example.local/test.html) 向http://api.example.com/v1/matches 发出请求时,我收到关于Access-Control-Allow-Origin 的错误。奇怪的是,请求确实通过了,因为信息通过基于 Laravel 的 API 正确存储在数据库中。
$.ajax({
method: 'POST',
url: 'http://api.example.com/v1/players',
data: {
"username": "username",
"first_name": "First",
"last_name": "Last",
"nickname": ""
}
}).always(function(r) {
console.log(r);
});
错误:
XMLHttpRequest cannot load http://api.example.com/v1/players. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://other.example.com' is therefore not allowed access.
console.log(r) 返回{readyState: 0, responseJSON: undefined, status: 0, statusText: "error"}
我使用 Homestead VM (API) 和 Vagrant 环境(应用程序)在本地开发了应用程序,它在这些环境中正常工作...
一些观察:
- 在我的 Chrome 开发者工具中,这些请求中的每一个都显示为方法:
POST,状态:200 OK,类型:xhr。 - Postman 和 PhpStorm 的 RESTful 服务测试器等工具可以正确执行请求,并且添加数据时不会出错。
欢迎任何有关如何进一步调试此问题的想法...我一整天都在努力解决这个问题,但我只是不知道是什么原因造成的。
【问题讨论】: