嗨,我是API制作和使用的新手,我使用Laravel作为api部件,并使用角的HttpClient来提出请求,下面是代码
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class ApitestProvider {
tests;
apiUrl = "http://127.0.0.1:8000/api";
testAdded;
testGotten;
testDeleted;
constructor(public http: HttpClient) {
console.log('Hello ApitestProvider Provider');
}
addTest(data) {
/*let nData= JSON.stringify(data);
console.log(nData);*/
let obj = {name : "test"};
this.http.post(this.apiUrl + "/tests",JSON.stringify(obj))
.subscribe(res => {
console.log(res);
this.testAdded = res;
}, (err) => {
console.log(err);
});
}
为了测试目的对代码进行了修改,下面是控制器的laravel代码。
public function store(Request $request){
return Testme::create($request->all());
}
下面是初始迁移的代码
class CreateTestmesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('testmes', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('testmes');
}
}
在模型中,唯一可填入的是“名称”,提前感谢。
发布于 2018-12-04 08:35:05
我发现了这个问题,我只需要在我发送的请求中设置数据格式的头。
只需使用httpheaders
addTest(data) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
let nData = JSON.stringify(data);
console.log(nData)
this.http.post(this.apiUrl + "/tests", nData, {headers: headers})
.subscribe(res => {
console.log(res);
this.testAdded = res;
}, (err) => {
console.log(err);
});
}
发布于 2018-12-04 08:16:47
错误是:“字段名没有默认值”。这意味着您不会在post请求中为该字段发送任何值。所以你有三种方法:
1 ->用客户端http请求中的值填充name字段
2 $table->string('name')->default('');应用程序中数据库用户的迁移,并将默认值设置为name字段,如下所示:
3 $table->string('name')->nullable();转到2°->的同一文件,并设置名称字段为空,如下所示:
https://stackoverflow.com/questions/53616786
复制相似问题