我正在使用ionic构建应用程序,该应用程序使用带有护照身份验证的laravel中的REST API。我的问题是,当我发出GET请求时,它工作得很好但是当我尝试使用PUT方法发送数据时,它总是返回“未经验证的”#。
我对不起作用的API的调用
update(data) {
let headers = new Headers({
'Content-Type': 'x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': this.token
});
return new Promise((resolve,reject)=>{
this.http.put(`${environment.API_ENDPOINT}/api/user`, {
headers: headers,
data: data
}).subscribe((result:any)=>{
resolve(result.json());
},(error:any)=>{
reject(error.json());
});
})
}
我的GET CALL有效
getCurrentUser() {
let headers = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': this.token
});
return this.http.get(`${environment.API_ENDPOINT}/api/user`, {
headers: headers
}).map(res => res.json());
}
关于LARAVEL routes / api.php
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/user', function(Request $request){
return $request->user();
});
Route::put('/user','UserController@update');
});
控制器上的更新方法
public function update(Request $request){
$user = User::find($request->user()->id);
$validator = Validator::make($request->all(),[
'nome'=> 'required|max:255',
'cpf' => 'required|max:14',
'telefoneCelular' => 'required',
]);
if($validator->fails()){
return response()->json(['message'=>$validator->errors()],400);
}else{
$user->nome = $request->input('nome');
$user->cpf = $request->input('cpf');
$user->telefoneCelular = $request->input('telefoneCelular');
if($user->save()){
return response()->json(['data'=>$user],201);
}else{
return response()->json(['message'=>'Erro ao atualizar usuário'],400);
}
}
}
PS:它适用于POSTMAN
答案 0 :(得分:0)
我弄清楚问题是我将错误的参数传递给this.http.put
这是可行的代码
update(data) {
let headers = new Headers({
'Content-Type': 'x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': this.token
});
console.log(headers);
return new Promise((resolve,reject)=>{
this.http.put(`${environment.API_ENDPOINT}/api/user`, data, {
headers: headers,
}).subscribe((result:any)=>{
resolve(result.json());
},(error:any)=>{
reject(error.json());
});
})
}