【问题标题】:Get api working in Postman but not with Axios让 api 在 Postman 中工作,但不能在 Axios 中工作
【发布时间】:2022-01-27 12:37:27
【问题描述】:

我正在学习 Udemy 的教程并被困在这里:

Yelp.js

import axios from "axios";

export default axios.create({
    baseURL : 'https://api.yelp.com/v3/businesses',
    headers : {
        Authorization : 
        'Bearer ****************'
    }
})

SearchScreen.js

const SearchScreen = () => {

    const [term, setTerm] = useState('');
    const [results, setResults] = useState([]);

    const searchApi = async () => {
        const response = await yelp.get('', {
            params : {
                term : term,
                location: 'san jose'
            }
        });
        setResults(response.data);
    }

    return (
        <View style={styles.backgroundStyle}>
            <SearchBar 
                term = {term} 
                onTermChange = {setTerm}
                onTermSubmit = {searchApi} />

            <Text>We have found {results.length} results</Text>
        </View>
    );
};

const styles = StyleSheet.create({
    backgroundStyle : {
        backgroundColor : '#FFFFFF',
        flex: 1
    }
})

export default SearchScreen

searchApi 被触发时,我在控制台中看到此错误

[Unhandled promise rejection: Error: Network Error]
at node_modules/axios/lib/core/createError.js:15:17 in createError
at node_modules/axios/lib/adapters/xhr.js:114:22 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

具有相同授权密钥的相同 Api 在 Postman 中工作。我在这里遗漏了什么吗?

【问题讨论】:

  • 我的不是 localhost url
  • 您可以尝试在您的searchApi() 中使用try{} catch(error){} 块,或者在您的axios.create 中添加timeout: 25000。希望对您有所帮助。
  • await yelp.get('') 真的应该是空的吗?尝试将整个 URL 放在那里,即使它不是“必要的”。像'127.0.0.1'或'localhost'

标签: react-native axios


【解决方案1】:

如果连接不是问题,则错误出在请求上,可能 API 试图让您知道错误代码但您没有捕获它。

像这样实现 try/catch:

try {
  const response = await yelp.get('', {
    params : {
        term : term,
        location: 'san jose'
    }
  });
  setResults(response.data); 
} catch (ex) {
  if (ex && ex !== undefined && ex.toString && ex.toString !== undefined) {
    // print the general exception
    console.log(ex.toString());
  }     
  if (
    ex.response &&
    ex.response !== undefined &&
    ex.response.data &&
    ex.response.data !== undefined
  ) {
    // print the exception message from axios response
    console.log(ex.response.data);
  }
}

然后检查您的控制台。

【讨论】:

    【解决方案2】:

    您需要使用 try catch 块来捕获错误。如果您没有收到任何错误,您还可以在 Web 浏览器的开发人员面板中检查网络 XHR 调用。在开发者面板中,您可以准确地看到 API 调用的 url、标头和正文,还可以看到从 API 收到的响应。

    Chrome 浏览器 -> https://developer.chrome.com/docs/devtools/open/

    火狐 -> https://developer.mozilla.org/en-US/docs/Tools/Web_Console

    如果您需要进一步的帮助,请随时从您的网络面板发布屏幕截图或将您的代码推送到 github 以进一步调试。

    【讨论】:

      【解决方案3】:

      很可能是CORS 错误。见Calling Yelp API from frontend JavaScript code running in a browser

      无法从具有 CORS 保护的浏览器运行该代码。如果必须,您可以尝试使用第三方浏览器扩展或其他方式禁用 CORS。 (风险自负!)

      【讨论】:

        【解决方案4】:

        通过活动开发者工具在网络选项卡中检查 XHR 请求。如果您在 API 中遇到错误。如果您得到正确的响应,则通过捕获异常来调试您的代码。

        【讨论】:

          【解决方案5】:

          @housefly

          我认为邮递员 GET 请求和您的 axios 请求之间的区别在于隐藏的标头。即使您没有提及,邮递员也有内部逻辑来附加请求类型和标题下方。由于您使用 Axios 的手动查询没有足够的标题。您能否在您的 axios API 调用中尝试以下标头。

          【讨论】:

            猜你喜欢
            • 2021-08-25
            • 2020-12-14
            • 1970-01-01
            • 1970-01-01
            • 2022-01-12
            • 1970-01-01
            • 2015-11-08
            • 1970-01-01
            • 2021-12-26
            相关资源
            最近更新 更多