位置 0 的 JSON 中的意外标记 < - 在 Angular2 应用程序中

Unexpected token < in JSON at position 0 - in Angular2 application

我正在编写一个带有 php 后端的 Angular2 应用程序。当我从 angular 应用程序向服务器发出请求时,它会在浏览器控制台中向我发送此错误消息。

Unexpected token < in JSON at position 0

我已阅读有关此问题的问题。他们说问题出在 http 响应的响应类型上。他们说,响应类型应该是json。但是在我的应用程序中响应类型是 text/html

这是与我的问题相关的 service.ts 文件 user.service.ts

import { Injectable } from '@angular/core';
import {User} from '../models/user';
import {Http} from '@angular/http';

@Injectable()
export class UserService {

  private currentUser: User;

  constructor(private http: Http) {
    this.currentUser = new User(null, null, null, false);
  }

  getCurrentUser() {
    return this.currentUser;
  }

  logIn(username, password) {
    let curUser = new User(username, password, null, false);

    this.http.post('http://localhost/back_End/controllers/user.php/', {'username': username , 'password': password})
      .map(res => res.json())
      .subscribe(
        users => {
          curUser = users[0];
          console.log(curUser);
        }
      );
    console.log(curUser);
}

问题与 logIn 方法有关。

这是对应的php文件user.php

<?php
$data  = json_decode(file_get_contents("php://input"));

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

$server_ame = "localhost";
$username = "root";
$password = "";
$dbname = "yathra";
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "select * from user where username='$data->username' and password='$data->password'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}else {
    echo "0 results";
}
echo json_encode($data);

$conn->close();
?>

我是 Angular2 的新手。有人可以给我一个解决方案吗?

您看到此错误是因为您试图将文件解析为 JSON,但事实并非如此:

.map(res => res.json())

尝试在 运行 res.json 之前记录您的回复,您会发现它是一个以 < 字符开头的非 JSON 文件(例如 php、XML、HTML 等)。

你可以试试这个:

问题出在这里,因为你使用 json() 而不是 json

  1. json() - 总是 return json
  2. json - 总是 return 文本(可能是 HTML,PHP,X HTML 等)。

    this.http.post('http://localhost/back_End/controllers/user.php/', {'username':用户名,'password':密码}) .map(res => res.json) // 看这里 。订阅( 用户 => { 当前用户=用户[0]; console.log(curUser); } );