首页 > 解决方案 > Axios 和纽约时报 API

问题描述

我正在使用 axios 从纽约时报搜索 API 获取数据,以便在我的 react 本机应用程序上使用,但由于某种原因,我一直得到空结果。这是我使用的代码:

在 nytimes.js 文件中:

import axios from "axios";

export default axios.create({
  baseURL: "https://api.nytimes.com/svc/search/v2",
  headers: {
    Authorization: "Bearer 'MY_API_KEY'",
  },
});

在我的 ResultDetails.js 文件中:

const [results, setResutls] = useState([]);
  const [errorMessage, setErrorMessage] = useState("");
  const searchApi = async (searchTerm) => {
    // wait for a reponse to get back once it does with some data we asign that data to the reponse variable
    try {
      const reponse = await nytimes.get("/articlesearch", {
        params: {
          //limit: 50,
          q: searchTerm, // q is term
          //
        },
      });
      setResutls(reponse.data.docs); //docs
    } catch (err) {
      setErrorMessage("Something went wrong");
    }
  };
  // bad code
  //searchApi("pasta");
  useEffect(() => {
    searchApi("covid");
  }, []);

我用<Text>{results.length}</Text>看看我是否得到任何结果。当我在 catch 块中使用 console.log(err) 时,我得到了这个:

Request failed with status code 404
- node_modules\axios\lib\core\createError.js:3:19 in <global>
- node_modules\axios\lib\core\settle.js:14:6 in settle
- node_modules\axios\lib\adapters\xhr.js:57:8 in handleLoad
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:566:23 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

标签: reactjsrestapireact-nativeaxios

解决方案


通过使用此代码,您可以使用您在评论区发送的数据调用 NYT 的 API。我列出了所有来自 API 的摘要

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';

import axios from 'axios';

export default function Home() {
  const [docs, setDocs] = useState([]);

  async function loadAPI() {
    const response = await axios.get(
      'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=election&api-key=h1TylVtDCbyqnZZWgBXfGhU0lXQr7Cw1'
    );

    setDocs(response.data.response.docs);
  }

  useEffect(() => {
    loadAPI();
  }, []);

  return (
    <View>
      {
        docs.map((article, index) => 
          <Text key={index}>
            {article.abstract}
          </Text>
        )
      }
    </View>
  );
}

推荐阅读