当前位置: 首页 > 后端技术 > PHP

CodeIgniter解决跨域问题

时间:2023-03-29 19:23:24 PHP

跨域问题一般都是在后端处理,也就是在服务端处理。我们以java为例。一般在返回给前端时,获取响应对象,并设置返回消息头中的Access-Control-Allow-Origin属性。代码示例为:response().setHeader("Access-Control-Allow-Origin","*");回到正题,最近选择了codeigniter作为后台服务器,用ci解决跨域问题也是类似的。在控制器中,按照以下步骤执行代码:header("Access-Control-Allow-Origin:*");//$this->output->set_header("Access-Control-Allow-Origin:*");//也可以这样写,不过个人推荐第一行这样写$this->output->set_output(json_encode(array("name"=>"hellowoody")));//返回json格式的消息,看起来真的很简单,也很相似,但是在解决过程中也遇到了一些问题。错误代码1echo'hellowoody';//header前使用echo语句,报php语法错误header("Access-Control-Allow-Origin:*");错误代码2echo'hellowoody';//在$this->output->set_header前后使用echo语句,前端报跨域错误$this->output->set_header("Access-Control-Allow-Origin:*");正确代码一$this->output->set_header("Access-Control-Allow-Origin:*");$this->output->set_output(json_encode(array("name"=>"hellowoody")));//以json格式返回消息的正确编码Twoheader("Access-Control-Allow-Origin:*");$this->output->set_output(json_encode(array("name"=>"hellowoody")));//返回json格式的消息