【发布时间】:2013-10-21 16:34:46
【问题描述】:
我正在使用 Codeigniter-restserver 为 Phonegap 中的移动应用程序开发 REST API。
由于 Phonegap 使用 file:// 加载 index.html,我的 API 应该支持 CORS。我是这个 CORS 的新手。
我在libraries/REST_Controller.php中设置了标题
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
我正在使用 Backbone.js。
这是我的控制器
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';
class Prop extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
function property_get()
{
...
}
function property_post()
{
...
}
function attach_image($file_type)
{
if($this->post($file_type) != ""){
save_base64_image($file_type,$this->post($file_type));
$this->email->attach($_SESSION[$file_type]);
}
}
function property_delete()
{
...
}
function share_post()
{
$email_id = $this->post('emailid');
$config['mailtype'] = "html";
$this->email->initialize($config);
$this->email->from('myid@gmail.com', 'mobile app');
$this->email->to($email_id);
$this->email->subject('subject');
$this->email->message('message');
if ( ! $this->email->send() )
{
$this->response("Internal server error.", 500);
}
else
{
$result = new stdClass();
$result->message = 'Email has been sent.';
$this->response($result, 200); // 200 being the HTTP response code
}
}
public function send_post()
{
var_dump($this->request->body);
}
public function send_put()
{
var_dump($this->put('foo'));
}
}
这是我的 jQuery ajax 调用。
$.ajax( {
url: PMSApp.apiUrl + "/share/format/json",
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(function(response) {
console.log(JSON.stringify(response));
})
.fail(function(response) {
console.log(JSON.stringify(response));
})
.always(function(response) {
console.log(JSON.stringify(response));
});
我可以使用 POSTMAN、chrome 扩展程序访问此 /share/format/json API,但不能使用 file:// 或 localhost://。
编辑:
我也尝试将share_post() 更改为share_gett(),它成功了。但我在 POST 中需要它。
在过去的 48 小时里,我一直坚持这一点。尝试了许多解决方案,但没有任何帮助我解决这个问题。请帮帮我。
【问题讨论】:
-
你是怎么解决的?
-
@Leandro phonegap 具有将您的域列入白名单的功能。需要在config.xml中设置
标签: rest backbone.js cordova cors codeigniter-restserver