首页 > 解决方案 > 通过 angular http post 将 json 数据发送到 laravel 控制器

问题描述

我是 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`))
);

}

有人可以给我建议吗?

标签: jsonangularlaravelhttppost

解决方案


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

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

推荐阅读