【发布时间】:2019-02-08 13:06:43
【问题描述】:
我的 api 使用 PHP Silex 发回这样的 JSON 响应:
{"response":true,"message":"Bla","userId":"AAA"}
但我无法在我的 Typescript 前端解析它
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>)
我使用 PHP 和 Silex 框架的 php 端点:
$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);
});
当尝试将 json 对象硬编码为代码时,它会解析!
更新解决方案 我不得不对 result.data 使用 trim() 来删除空格,somehome 的响应带有空格,而 JSON 不喜欢这样。谢谢大家的帮助。
【问题讨论】:
-
可能是空格使用 trim()
-
console.log(typeof result.data);? -
@DieterKräutl 但 JSON 标记之间允许有空格
-
数据好像已经解析过了。
-
console.log(result.data.message)显示什么?
标签: javascript php json typescript silex