首页 > 解决方案 > 流明:具有默认值的新记录已添加到数据库

问题描述

我是 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。

标签: phpvue.jslumen

解决方案


您的问题是您正在更改content type请求的内容。不要写headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, asaxios发送 this as 'Content-Type': 'application/json',所以当它到达 Lumen 时,它会正确“解码”它,您可以执行$request->all()并获取您想要的任何数据。您甚至不必编写任何content-type标题,axios在这种情况下,这一切都是自动完成的。

所以你的javascript代码应该是这样的:

async createPerson() {
  await axios.post('/api/persons/', {
    firstName: 'Edward',
    lastName: 'Edwardson',
    address: 'Address8'
  })
},

推荐阅读