通过角度HTTP发送json数据到laravel控制器

时间:2018-11-09 06:26:57

标签: json angular laravel http post

我是laravel和angular的新手。我试图将一些数据从服务发送到laravel控制器中的函数。 这是我的Laravel代码:

public function authenticate(Request $request){
    file_put_contents('test.txt','run');

    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
    header('Access-Control-Allow-Credentials: true');

    $name=$request->input('name');
    $password=$request->input('password');
    $message='Not Found';

    $user=User::where(['name'=>$name])->first();
    if($user->checkPasswordAttribute($password)){
        $message='Found';
    }
    return response()->json([
        'message' => $message,
    ]);
}

这里是我通过json提供的角度服务代码:

login(user: User): Observable<User> {
return this.http.post<User>(this.usersUrl, user, httpOptions).pipe(
  tap( _ => this.log('fetched user')),
  catchError(this.handleError<User>(`getUser`))
);

}

与此HttpHeaders:

const httpOptions = {  headers: new HttpHeaders({ 'Content-Type':  'application/json' })};

上面的代码没有发送任何东西,甚至没有运行file_put_content,我为测试添加了该代码。 但是,当我在angular服务中将formData用作以下代码时,一切正常,然后运行我的后端代码。

login(user: User): Observable<User> {
const postData = new FormData();
postData.append('name', user.name);
postData.append('password', user.password);
return this.http.post<User>(this.usersUrl, postData).pipe(
  tap( _ => this.log('fetched user')),
  catchError(this.handleError<User>(`getUser`))
);

}

有人可以建议我吗?

1 个答案:

答案 0 :(得分:0)

这将解码http请求json有效负载。

$data = json_decode($request->getContent(), true);