nodejs API извлечения возвращает тот же файл JSON - PullRequest
1 голос
/ 08 апреля 2020

Я пытаюсь выучить nodejs, создав собственный API для отдыха.

Я скопировал этот код с https://sweetalert.js.org/guides/#getting, начал :

swal({
  text: 'Search for a movie. e.g. "La La Land".',
  content: "input",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(name => {
  if (!name) throw null;

  return fetch(`https://itunes.apple.com/search?term=${name}&entity=movie`);
})
.then(results => {
  return results.json();
})
.then(json => {
  const movie = json.results[0];

  if (!movie) {
    return swal("No movie was found!");
  }

  const name = movie.trackName;
  const imageURL = movie.artworkUrl100;

  swal({
    title: "Top result:",
    text: name,
    icon: imageURL,
  });
})
.catch(err => {
  if (err) {
    swal("Oh noes!", "The AJAX request failed!", "error");
  } else {
    swal.stopLoading();
    swal.close();
  }
});

и я пытаюсь сделать fetch, используя nodejs.

. Для этого я изменил строку

return fetch(`https://itunes.apple.com/search?term=${name}&entity=movie`);

на

return fetch('http://localhost:3000/search?movie_name=' + name, {
                method: 'GET'
            });

(я настроил приложение на прослушивание через порт 3000).

и в своем файле nodejs я добавил маршрут GET:


app.get('/search', async function(req, resp) {
    try {
        let name = req.query.name;
        let response = await fetch('https://itunes.apple.com/search?term=' + name + '&entity=movie');
        let body = await response.text();
        let json = JSON.parse(body);
        resp.status(200).send(json);
    } catch (error) {
        resp.status(500).send();
    }
});

Проблема в том, что нет независимо от того, что я ввожу в качестве ввода, я получаю тот же JSON файл обратно.

Я совершенно новичок в nodejs и ценю всю помощь!

JSON файл, который Я продолжаю получать с любого ввода (например, http://localhost: 3000 / поиск? Movie_name = bob ):

{"resultCount":2,"results":[{"wrapperType":"track","kind":"feature-movie","trackId":1469900435,"artistName":"Barak Goodman","trackName":"Woodstock: Three Days that Defined a Generation","trackCensoredName":"Woodstock: Three Days that Defined a Generation","trackViewUrl":"https://itunes.apple.com/us/movie/woodstock-three-days-that-defined-a-generation/id1469900435?uo=4","previewUrl":"https://video-ssl.itunes.apple.com/itunes-assets/Video113/v4/23/21/ff/2321ffa0-9389-63f8-1521-59de6b73ac87/mzvf_6812907527133973755.640x480.h264lc.U.p.m4v","artworkUrl30":"https://is3-ssl.mzstatic.com/image/thumb/Video123/v4/b5/cc/e1/b5cce1ab-e415-7084-c9e9-9dfcf512374c/source/30x30bb.jpg","artworkUrl60":"https://is3-ssl.mzstatic.com/image/thumb/Video123/v4/b5/cc/e1/b5cce1ab-e415-7084-c9e9-9dfcf512374c/source/60x60bb.jpg","artworkUrl100":"https://is3-ssl.mzstatic.com/image/thumb/Video123/v4/b5/cc/e1/b5cce1ab-e415-7084-c9e9-9dfcf512374c/source/100x100bb.jpg","collectionPrice":4.99,"trackPrice":4.99,"trackRentalPrice":4.99,"collectionHdPrice":5.99,"trackHdPrice":5.99,"trackHdRentalPrice":4.99,"releaseDate":"2019-08-06T07:00:00Z","collectionExplicitness":"notExplicit","trackExplicitness":"notExplicit","trackTimeMillis":5845247,"country":"USA","currency":"USD","primaryGenreName":"Documentary","contentAdvisoryRating":"Unrated","shortDescription":"Celebrate the 50th anniversary of the concert that became a touchstone for a generation. This film","longDescription":"Celebrate the 50th anniversary of the concert that became a touchstone for a generation. This film brings the concert to life through the voices of those who were present at what became the defining moment of the counterculture revolution."},{"wrapperType":"track","kind":"feature-movie","trackId":648772372,"artistName":"Laura Archibald","trackName":"Greenwich Village: Music that Defined a Generation","trackCensoredName":"Greenwich Village: Music that Defined a Generation","trackViewUrl":"https://itunes.apple.com/us/movie/greenwich-village-music-that-defined-a-generation/id648772372?uo=4","previewUrl":"https://video-ssl.itunes.apple.com/itunes-assets/Video118/v4/1d/fc/ce/1dfcce43-f789-7baf-48d9-998b3b264692/mzvf_2471105163605910750.640x480.h264lc.U.p.m4v","artworkUrl30":"https://is4-ssl.mzstatic.com/image/thumb/Video2/v4/fc/3b/87/fc3b8703-8069-6646-f99e-fcfa8bed70c8/source/30x30bb.jpg","artworkUrl60":"https://is4-ssl.mzstatic.com/image/thumb/Video2/v4/fc/3b/87/fc3b8703-8069-6646-f99e-fcfa8bed70c8/source/60x60bb.jpg","artworkUrl100":"https://is4-ssl.mzstatic.com/image/thumb/Video2/v4/fc/3b/87/fc3b8703-8069-6646-f99e-fcfa8bed70c8/source/100x100bb.jpg","collectionPrice":9.99,"trackPrice":9.99,"trackRentalPrice":4.99,"collectionHdPrice":12.99,"trackHdPrice":12.99,"trackHdRentalPrice":4.99,"releaseDate":"2013-06-18T07:00:00Z","collectionExplicitness":"notExplicit","trackExplicitness":"notExplicit","trackTimeMillis":5541875,"country":"USA","currency":"USD","primaryGenreName":"Documentary","contentAdvisoryRating":"Unrated","shortDescription":"An all-star cast of characters including Pete Seeger, Carly Simon, Richie Havens and Susan Sarandon","longDescription":"An all-star cast of characters including Pete Seeger, Carly Simon, Richie Havens and Susan Sarandon came together in ‘60s Greenwich Village creating a social, cultural and political vortex through their desire to make change. Their stands against social and racial injustice through words and music went beyond their celebrity to create an everlasting effect on generations to come.  A FilmBuff Presentation."}]}

Пожалуйста, обратите внимание:

sweetAlert - это замена функции window.alert () в JavaScript, которая показывает очень симпатичный модальный windows. Это отдельная библиотека, которая не имеет зависимостей и состоит из файла JavaScript и файла CSS.

определение

1 Ответ

1 голос
/ 08 апреля 2020

Кажется, опечатка: вместо вызова запроса с name вы звоните с movie_name. Который не совпадает с req.query.name; в express js.

Браузер

return fetch('http://localhost:3000/search?movie_name=' + name, {
                method: 'GET'
            });

Expressjs:

app.get('/search', async function(req, resp) {
    try {
        let name = req.query.name;
...