In a register component. I can register a new user but I got a json.parse error. I tested the component with postman and it is ok. but I dont know why the json is bad.
register.component.ts
this.user = this.forma.value;
this._userService.signup(this.user).subscribe(
{
next: (response) =>
{
console.log(response);
console.log(this.forma);
if(response.status == "success")
{
this.status = response.status;
this.forma.reset();
}
else
{
this.status = 'error';
console.log("error status", this.status);
}
},
error: (error) =>
{
console.log(<any>error);
}
});`enter code here`
user.service.ts
signup(user, gettoken = null):Observable<any>
{
if(gettoken != null)
{
user.gettoken = 'true';
}
let json = JSON.stringify(user);
let params = 'json='+json;
console.log(params);
let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this.url+'login', params, {headers:headers});
}
I forgot to say that the jwt token is added to the json
{
"error": {},
"text": "array(2) {n ["email"]=>n string(17) "[email protected]"n ["password"]=>n string(8) "password"n}n"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImVtYWlsIjoibWFydGFAZXhhbXBsZS5jb20iLCJuYW1lIjoibWFydGEiLCJzdXJuYW1lIjoibWVqaWEiLCJpYXQiOjE2NzM4NjIxODgsImV4cCI6MTY3NDQ2Njk4OH0.aGIE_5peskBjbTSA3GSaHJukq0yL_EpSaOIMOE8JUzg""
}
this is the method on the backend with laravel
public function login(Request $request)
{
$jwtAuth = new JwtAuth();
// recibir datos por post
$json = $request->input('json', null);
$params = json_decode($json);
$params_array = json_decode($json, true);
var_dump($params_array);
// validar esos datos
$validate = Validator::make($params_array, [
'email' => 'required|email',
'password'=> 'required'
]);
if($validate->fails())
{
$signup = array(
'status' => 'error',
'code' => 404,
'message' => 'el usuario no se ha podido identificar',
'errors' =>$validate->errors()
);
}
else
{
// cifrar la password
$pwd = hash('sha256', $params->password);
// devolver token o datos
$signup = $jwtAuth->signup($params->email, $pwd);
if(!empty($params->gettoken))
{
$signup = $jwtAuth->signup($params->email, $pwd, true);
}
}
return response()->json($signup, 200);
}
2
Answers
Frontend
Backend
Think you should use
application/json
as aContent-Type
Edit