CodeIgniter对接Vue无法获取post值问题

要使用 Vue 前端+ CodeIgniter 后端这种方式,第一个是跨域问题,从网上抄了一段写的挺详细的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 1、对普通的GET/POST/PUT请求,请求头设置如下:
// 设置json格式请求头
header("Content-type:application/json; charset=utf-8");
//跨域请求允许的域名设置,因为需要传递cookie,不能使用*
header("Access-Control-Allow-Origin: *");
// 跨域请求允许的请求头
header("Access-Control-Allow-Headers: Content-type");
// 跨域请求同意发送Cookie
header("Access-Control-Allow-Credentials: true");

// 2、非简单请求每次请求前,都会发送一个一次”预检“请求,它是 options的请求方式。它主要是询问服务器是否允许这个非简单请求访问,如果我们允许,则返回所需要的回应头信息(response header),这个预检请求的请求头设置如下:
//设置json格式请求头
header("Content-type:application/json; charset=utf-8");
// 跨域请求允许的域名设置
header("Access-Control-Allow-Origin: *");
// 跨域请求允许的请求头
header("Access-Control-Allow-Headers: Content-type");
header("Vary: Accept-Encoding, Origin");
// 跨域请求同意发送Cookie
header("Access-Control-Allow-Credentials: true");
// options请求中所允许的方法
header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
// OPTIONS这个预请求的有效时间,20天
header("Access-Control-Max-Age: 1728000");

但对于这里来说不用那么复杂,只需要设置 Access-Control-Allow-Origin 就行了,CI 的写法:

1
$this->output->set_header("Access-Control-Allow-Origin: *");//"*"改为网站地址

Vue 中:

1
2
3
4
5
6
7
let data= {
name: this.name,
email: this.email
};
axios.post("http://localhost/test/", data).then(res => {
console.log(res);
});

CodeIgniter 中:

1
2
3
4
5
6
7
8
9
public function test(){
$name = $this->input->post('name');
$email = $this->input->post('email');
$arr = array(
'name' => $name,
'email' => $email
);
echo json_encode($arr);
}

试了试发现 Vue 正常,也能收到返回值,但 CI 却没办法收到 post 的数据,直接返回 null ,

后来发现 axios 里面写着:

会默认序列化 JavaScript 对象为 JSON。 如果想使用 application/x-www-form-urlencoded 格式,你可以使用下面的配置。
1
2
3
4
5
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
......

把 Vue 部分改一下就行了:

1
2
3
4
5
6
let params = new URLSearchParams();
params.append("name", this.name);
params.append("email", this.email);
axios.post("http://localhost/test/", params).then(res => {
console.log(res);
});