意外的令牌<在位置0的JSON中(Angular2和php)

时间:2017-02-13 16:02:26

标签: php json angular

我无法摆脱这个问题,现在我基本上只是从一个问题跳到另一个问题。我正在尝试向我的xampp服务器发送一个帖子请求,但无法使其正常工作。我正在按照不同的教程将它们组合在一起,但是有一个我无法弥合的差距。

Unexpected token < in JSON at position 0

时的错误

角度组件:

onSubmit(Username:string, Password:string) {
    this.httpService.sendData({Username: Username, Password:Password})
        .subscribe(
            data => console.log(data)
        );
 }

角度服务

@Injectable()
export class HttpService {

  constructor(private http: Http) { }

  sendData(user:any)    {
    console.log(user);
    const body = JSON.stringify(user);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    return this.http.post('http://nlr/api/customer/add',body, {
        headers: headers
    })
    .map((data: Response) => data.json());
  }

}

php代码

$app->post('/api/customer/add', function(Request $request, Response $response) {

    $data = $request->getParsedBody();
    $Username = filter_var($data['Username'], FILTER_SANITIZE_STRING); //These 4 lines seem to give a problem
    $Password = filter_var($data['Password'], FILTER_SANITIZE_STRING);
    $Other = filter_var($data['Other'], FILTER_SANITIZE_STRING);
    $Leaning = filter_var($data['Leaning'], FILTER_SANITIZE_STRING);

    //$Username = $request->getParam('Username');
    //$Password = $request->getParam('Password');
    //$Other = $request->getParam('Other');
    //$Leaning = $request->getParam('Leaning');

    $sql = "INSERT INTO firsttb (Username, Password, Other, Leaning) VALUES (:Username, :Password, :Other, :Leaning)";

    try{
        // Get DB Object
        $db = new db();
        //Connect
        $db = $db->connect();

        $stmt = $db->prepare($sql);

        $stmt->bindParam(':Username', $Username);
        $stmt->bindParam(':Password', $Password);
        $stmt->bindParam(':Other', $Other);
        $stmt->bindParam(':Leaning', $Leaning);

        $stmt->execute();

        echo '{"notice": {"text": "User added"}';

    } catch(PDOExeption $e) {
        echo '{"error: {"text": '.$e->getMessage().'}';

    }
});

?>

任何帮助将不胜感激!

0 个答案:

没有答案