【发布时间】:2021-10-27 09:18:19
【问题描述】:
我是 PHP 新手,我尝试制作小型测试全栈项目。我在客户端(前端)上有 Vue.js 应用程序,在服务器(后端)上有 PHP(流明)。代码如下:
客户:
Vue 组件:
async createPerson() {
const optionAxios = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
try {
await axios.post(`http://localhost:8000/api/persons/`, {
firstName: 'Edward',
lastName: 'Edwardson',
address: 'Address8'
}, optionAxios)
} catch (error) {
console.log(error)
}
},
服务器:
路由器:
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('persons', ['uses' => 'PersonController@create']);
});
型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
protected $connection = 'mysql';
protected $table = 'person';
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
protected $fillable = [
'firstName', 'lastName', 'address'
];
protected $hidden = [];
}
控制器:
<?php
namespace App\Http\Controllers;
use App\Person;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PersonController extends Controller
{
public function __construct() {
header("Access-Control-Allow-Origin: *");
}
public function create(Request $request)
{
$person = Person::create($request->all());
error_log($person);
return response()->json($person, 201);
}
}
数据库:
在服务器端调试会话 - $request 值:
问题是新记录已添加到数据库中,但我在数据库级别设置了默认值。我不知道为什么我传递给客户端的对象没有被添加。
{
firstName: 'Edward',
lastName: 'Edwardson',
address: 'Address8'
}
最后一件事 - 如果我使用 Postman,它就可以工作。但是,如您所见,它不适用于 Axios。
【问题讨论】:
-
你从调试中得到了什么(
error_log),什么返回到前端?我假设“我在数据库上设置的默认值”,您的意思是所有字段都设置为“默认”? -
通过使用 error_log($request) 我得到了正确的对象值。是的,数据库中的所有值都设置为“默认”。
-
只是为了清楚起见-您能否添加已写入数据库的屏幕截图? (即从 SQL UI 中的“浏览”选项卡)。
-
我刚刚添加了表格的屏幕截图。
-
愚蠢的问题 - 您截取的调试日志显示了在数据库屏幕截图中使用主键
9写入的确切记录......肯定是由 PHP 调试创建的default记录显示在另一个屏幕截图中?