【问题标题】:Lumen: The new record with default values was added to database流明:具有默认值的新记录已添加到数据库
【发布时间】: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 记录显示在另一个屏幕截图中?

标签: php vue.js lumen


【解决方案1】:

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

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

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

【讨论】:

  • 由于 CORS 问题,我添加了该标头。
  • 这应该与 COR 无关。如果您必须添加它,那么您的问题在于负责它的middleware(流明,而不是 Javascript 或 Axios)。
  • 我刚刚从客户端删除了 Axios 选项并在后端设置了中间件,一切正常。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 2017-01-01
  • 1970-01-01
相关资源
最近更新 更多