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块中控制台.log(错误(时,我得到的是:

Request failed with status code 404
- node_modulesaxioslibcorecreateError.js:3:19 in <global>
- node_modulesaxioslibcoresettle.js:14:6 in settle
- node_modulesaxioslibadaptersxhr.js:57:8 in handleLoad
- node_modulesevent-target-shimdistevent-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:566:23 in setReadyState
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:190:12 in emit
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:436:47 in __callFunction
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:111:26 in __guard$argument_0
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:384:10 in __guard
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

通过使用此代码,您可以使用在评论区发送的数据调用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>
);
}

最新更新