php - 流明:具有默认值的新记录已添加到数据库
问题描述
我是 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。
解决方案
您的问题是您正在更改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'
})
},
推荐阅读
- android - Firebase Cloud Messaging - 类型不匹配:推断类型为 Message 但预期为 RemoteMessage
- c++ - grpc over tls:多个服务器证书
- python - 有没有更好的方法来构建这个刮?
- swift - 如何快速将字典保存到 Firebase?
- recursion - 在 F# 中为两个列表定义 zip 函数
- java - 我已将 java mysql 连接器添加到我的项目中,但我的项目仍然无法使用它
- javascript - 在 MathJax 中格式化纯数学表达式
- python - 行的最后一个值的百分位数
- java - 如何在非属性泛型类中覆盖 equals 方法?
- python - 将 pymongo 集合导出到 JSON 文件