Json 以laravel作为api的主干不返回错误
我创建了一个简单的主干脚本,它依赖于使用laravel RESTful功能创建的简单api。包含主干脚本的html驻留在我的桌面上,服务器api驻留在我的xampp本地主机上 关于拉威尔:Json 以laravel作为api的主干不返回错误,json,backbone.js,laravel,Json,Backbone.js,Laravel,我创建了一个简单的主干脚本,它依赖于使用laravel RESTful功能创建的简单api。包含主干脚本的html驻留在我的桌面上,服务器api驻留在我的xampp本地主机上 关于拉威尔: /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $task = Task::find($id);
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$task = Task::find($id);
return $task;
}
在主干上:
(function(){
App = {
Models : {},
Views : {},
Collections : {}
};
App.Models.Task = Backbone.Model.extend({
defaults : {title : '', active : 0},
urlRoot : 'http://localhost/api/public/tasks'
});
var task = new App.Models.Task({id : 1});
task.fetch();
//task.set({title : 'new tite', active : 1});
//task.save();
})();
服务器端连接正常,因为在测试时返回正确的json对象,但当我尝试运行主干脚本时,在开发控制台中出现以下错误:
> XMLHttpRequest cannot load http://localhost/api/public/tasks/1. No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'null' is therefore not allowed access
。
有什么问题吗?也许有人会需要这个 感谢TonyArra我找到了答案:
- 由于服务器和请求脚本位于两个不同的域上,因此解决方案如下:
- 在服务器上添加此代码(使用laravel,我在restful控制器的构造函数中添加了此代码):
$http_origin = $_SERVER['HTTP_ORIGIN'];
//if you trust origin set header else verify source
//if ($http_origin == "http://www.domain1.com")
header("Access-Control-Allow-Origin: $http_origin");