Axios - 请求失败,状态代码为 400 错误

Axios - Request failed with status code 400 error

我不知道为什么我在尝试访问 yelp api.

时收到 400 错误请求错误
Request failed with status code 400
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\core\settle.js:16:9 in settle
- node_modules\axios\lib\adapters\xhr.js:52:6 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

这是我使用提到的 baseURL 创建 axios 的代码:

import axios from "axios";
const apiKey =
  "<API KEY HERE>";

export default axios.create({
  baseURL: "https://api.yelp.com/v3/businesses",
  headers: {
    Authorization: `Bearer ${apiKey}`
  }
});

我正在从另一个名为 SearhcScreen 的组件发出特定术语的搜索请求:

import { View, Text, StyleSheet } from "react-native";
import SearchBar from "../components/SearchBar";
import yelp from "../api/yelp";

const SearchScreen = () => {
  const [term, setTerm] = useState("");
  const [results, setResults] = useState([]);

  const searchApi = async () => {
    try {
      const response = await yelp.get("/search", {
        params: {
          term,
          limit: 50,
          location: "karachi"
        }
      });
      setResults(response.data.businesses);
    } catch (e) {
      console.log(e);
    }
  };
  return (
    <View>
      <SearchBar
        term={term}
        onTermChange={newTerm => setTerm(newTerm)}
        onTermSubmit={() => searchApi()}
      />
      <Text>Search Screen</Text>
      <Text>We have found {results.length} results.</Text>
    </View>
  );
};

const styles = StyleSheet.create({});

export default SearchScreen;

我已经检查过 yelp 提供的 API 密钥是否正确,并在那里验证了我的开发者帐户。但是 运行 / 通过 axios 从 yelp api 检索列表仍然没有运气。

Yelp.com 无法找到您的位置 karachi。所以他们 return LOCATION_NOT_FOUND 根据你的 get 请求出错。

您可以通过将您的位置更改为 New York 来测试它。

yelp.get("/search", {
  params: {
    term,
    limit: 50,
    location: "New York"
  }
})

因此请根据您所在的位置提供您的纬度和经度,以指定更准确的位置。确保将这些值提供为 decimal

yelp.get("/search", {
  params: {
    term,
    latitude: 24.86,
    longitude: 67.01,
    limit: 50,
  }
});

希望对您有所帮助。有疑问欢迎留言。