My api sends back a JSON response like this using PHP Silex:
{"response":true,"message":"Bla","userId":"AAA"}
But i can't parse it in my Typescript frontend
this.authService.login(body).then((result : any) => {
console.log(result.data); // => {"response":true,"message":"Bla","userId":"AAA"}
let parsed = JSON.parse(result.data);
console.log(parsed.message); // => throws "SyntaxError: Unexpected token in JSON at position 0\n at JSON.parse (<anonymous>)
My php endpoint using PHP and Silex Framework:
$app->post('/user/login', function (Request $request) use ($app, $config) {
$email = $request->request->get('user-email');
$password = $request->request->get('user-password');
$rsp = loginUser($email,$password);
return $app->json($rsp);
});
When try and hardcode the json object into code, it does parse!
UPDATE SOLUTION I had to use trim() for result.data to remove whitespaces, somehome the response came with whitespaces and JSON didn't like that. Thank you all for your help.
SOLUTION
i used result.data.trim() for it to work, somehow the response had whitespaces and JSON didn't like that.
You may have a \u0000
char somewhere coming from your PHP code.
Try to remove these characters from your JSON string as soon as you get it from PHP:
this.authService.login(body).then((result : any) => {
string = result.data.replace("\u0000", "");
string = string.replace("\\u0000", "");
let parsed = JSON.parse(string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With