Попытка получить данные JSON из API, а затем опубликовать на сайте Angular 6 - PullRequest
0 голосов
/ 05 июля 2018

Я использую Uploadcare API загрузки, и я создаю приложение для загрузки фотографий, а затем добавляю их на мой сайт localhost. Я получаю сообщение об ошибке консоли:

Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.push../node_modules/@angular/http/fesm5/http.js.Body.json

Если кто-то может найти ошибку в моем коде и указать мне правильное направление, я, безусловно, был бы признателен за это. Код компонента следующий:

import { Component, OnInit, Input } from '@angular/core';
import { Http } from '@angular/http';

import { GalleryComponent } from '../gallery/gallery.component';

@Component({
  selector: 'app-fileuploader',
  templateUrl: './fileuploader.component.html',
  styleUrls: ['./fileuploader.component.css']
})
export class FileuploaderComponent implements OnInit {

  ngOnInit() {}

  @Input()
    gallery: GalleryComponent;

  constructor(private http: Http) { }

  uploadFile(event) {
    let elem = event.target;
    if(elem.files.length > 0) {
      let formData = new FormData();
      formData.append('file', elem.files[0]);

      this.http.post('http://localhost/angular-php/script.php', formData).subscribe((data) => {

        let jsonResponse = data.json();

        this.gallery.gotSomeDataFromTheBackend(jsonResponse.file);
        console.log('Got some data from the backend ', data);
      }, (error) => {
        console.log('Error! ', error);
      });

    }
  }
}

и PHP это:

<?php
header('Access-Control-Allow-Origin: *');
define(PUBLIC_KEY, 'cfcc5bbc8eb856a7d808');

$tempPath = $_FILES['file']['temp_name'];
$actualName = $_FILES['file']['name'];

$actualPath = dirname(_FILE_)."/temp/".$actualName;
move_uploaded_file($tempPath, $actualPath);


$ch = curl_init();

$post = [
  'UPLOADCARE_PUB_KEY'=>PUBLIC_KEY,
  'UPLOADCARE_STORE'=>1,
  'file'=> curl_file_create($actualPath)
];

curl_setopt($ch, CURLOPT_URL, 'https://upload.uploadcare.com/base/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$response = curl_exec($ch);

echo ($response);

Размещение console.log (data); прежде чем позволить JSON ..., я получаю:

Response {_body: "<br />↵<b>Warning</b>:  Use of undefined constant …ngular-php\script.php</b> on line <b>9</b><br />↵", status: 200, ok: true, statusText: "OK", headers: Headers, …}

headers
:
Headers {_headers: Map(1), _normalizedNames: Map(1)}

ok
:
true

status
:
200

statusText
:
"OK"

type
:
2

url
:
"http://localhost/angular-php/script.php"

_body
:
"<br />↵<b>Warning</b>:  Use of undefined constant PUBLIC_KEY - assumed 'PUBLIC_KEY' (this will throw an Error in a future version of PHP) in <b>C:\xampp\htdocs\angular-php\script.php</b> on line <b>4</b><br />↵<br />↵<b>Notice</b>:  Undefined index: temp_name in <b>C:\xampp\htdocs\angular-php\script.php</b> on line <b>6</b><br />↵<br />↵<b>Warning</b>:  Use of undefined constant _FILE_ - assumed '_FILE_' (this will throw an Error in a future version of PHP) in <b>C:\xampp\htdocs\angular-php\script.php</b> on line <b>9</b><br />↵"

__proto__
:
Body
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...