我正在使用Codeigniter-restserver为Phonegap中的移动应用程序开发REST。
由于Phonegap使用file://加载index.html,所以我的API应该支持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(),它起了作用。但我需要邮寄。
在过去的48小时里我一直被困在这上面。尝试了许多解决方案,但在这个问题上没有任何帮助。请帮帮我。
发布于 2014-09-20 19:23:48
Phonegap提供了白名单您的webservice域的选项。它是在config xml index.md.html中设置的访问源。
发布于 2013-10-14 07:47:37
https://stackoverflow.com/questions/19354682
复制相似问题