场景问题描述:
vue的axios请求,同样的代码,发送给thinkphp6,数据库录入是一条
发送给thinkphp5,数据库录入是两条,第一条是空白的,第二条是真实的
浏览器是发起一个请求的浏览器截图
// 对接tp6后端的写法
// vue代码
var data = {
title: '模板22',
colors: '{"0":"蓝色"}',
number: 11
}
axios.post('/api/adminmb/Productlist/create', data)
.then(function(response) {
console.log(response)
})
.catch(function(error) {
console.log(error)
})
// thinkphp6代码
//控制器
public function create()
{
$data = Request::param();
$res = Product::createDo($data);
if ($res) {
return self::returnMsg(200, 'success',$data);
} else {
return self::returnMsg(401, 'fail',$data);
}
}
//模型
public static function createDo($data)
{
if(!empty($data['id'])){
$result = Product::update($data,['id'=>$data['id']]);
}else{
$result = Product::create($data);
}
return $result;
}
结果是录入正常的一条数据
//对接tp5的写法
//vue代码
var data = {
title: '模板22',
colors: '{"0":"蓝色"}',
number: 11
}
axios.post('/api/adminmb/Productlist/create', data)
.then(function(response) {
console.log(response)
})
.catch(function(error) {
console.log(error)
})
//thinkphp5写法
//控制器
public function create()
{
$data = $_POST;
$CrmProduct = new CrmProduct();
$CrmProduct->allowField(true)->save($data);
$this->return_res($data);
}
结果是录入两条数据,第一条是空白的,第二条是真实的
- 数据库截图
- 服务器用Nginx,跨域解决:
set $cors_origin "";
if ($http_origin ~* "^http://localhost:8080$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;
add_header Access-Control-Allow-Headers X-Requested-With,X-Token,Content-Type,Accept,Origin;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
- 排查方案
1、用apipost工具接口录入后端,测试正常,录入一条数据
2、用jQuery的写法录入后端,测试正常,录入一条数据
- apipost工具截图
- jQuery写法代码
<script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
var data = {
title: '模板22',
colors: '{"0":"蓝色"}',
number: 11
}
var url='/api/adminmb/Productlist/create';
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data,
success: function (response, status) {
if(response.code){
//获取数据成功
alert(response.data.title);
}else{
//返回错误数据
alert(response.data);
}
},
error:function(xhr,status,error){
//返回数据异常
alert('返回数据异常!');
}
});
});
</script>