json - 通过 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`))
);
}
有人可以给我建议吗?
解决方案
这将解码 http 请求 json 有效负载。
$data = json_decode($request->getContent(), true);
推荐阅读
- anylogic - AnyLogic中的自定义红绿灯算法
- conv-neural-network - 如何在pytorch的MultiClass分类模型中预测标签?
- python - Flask - 如何按类型检索输入的值?
- spring-integration - How to pass object associated with message past outbound channel adapter
- python - 如何为单元测试套件做一个设置
- javascript - 让光标出现在输入焦点上
- opengl - 无法在 Opengl 2.x 中正确配置顶点属性
- hyperledger-fabric - Hyperledger Fabric - collections_config.json 不尊重私有数据收集
- reactjs - React Router 在组件之间共享数据
- html - 如何使我的菜单正确响应