标签: axios

无法使用 try 和 catch 处理 axios 中的 404 错误

我一直在尝试构建一个天气应用程序,但在验证 http 状态时遇到一些麻烦,以防用户自愿插入不存在的城市名称或用户在输入字段中输入错误。

唯一的问题是我找不到在 axios Promise 中插入 status !== 200 的方法。

200 状态工作得很好,但 404 状态却不行。我确信承诺中的某个地方有错误,但我无法找到解决方法。

此外,当我控制台记录错误时,它会显示以下消息:

console.log 中出现错误

Uncaught (in promise) Error: Request failed with status code 404
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.E (xhr.js:66)
Run Code Online (Sandbox Code Playgroud)

JavaScript

try{            
            axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}`).then(
                
            async response => {
                
            let data = await response.data

            if (response.status !== 200) {
            
                throw new Error(response.status);
            
                } else {
            
            console.log(data)
            document.getElementById('hum').textContent = data.main.humidity;
            document.getElementById('feels-like').textContent = data.main.feels_like;
                }}
        )
        
        } catch(error) {
            if (response.status === 404) {
                console.log(`Err: ${error}`);
                throw …
Run Code Online (Sandbox Code Playgroud)

api promise http-status-code-404 axios

0
推荐指数
1
解决办法
6459
查看次数

如何在useEffect中使用axios请求测试react组件?

我已在 useEffect 中对功能组件做出反应。 https://codesandbox.io/s/nifty-dew-r2p1d?file=/src/App.tsx

const App = () => {
  const [data, setData] = useState<IJoke | undefined>(undefined);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    axios
      .get("https://v2.jokeapi.dev/joke/Programming?type=single")
      .then((res: AxiosResponse<IJoke>) => {
        setData(res.data);
      })
      .catch((err) => console.log(err))
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <div className="App">
      {isLoading ? (
        <h2>Loading...</h2>
      ) : (
        <div className="info">
          <div className="info__cat">
            {data?.category ? `category: ${data.category}` : "bad category"}
          </div>
          <div className="info__joke">
            {data?.joke ? `joke: ${data?.joke}` : "bad data"}
          </div>
        </div>
      )}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

如何通过测试覆盖组件?我需要在请求之前、及时和之后测试状态。在这种情况下如何模拟请求?

typescript reactjs jestjs axios react-testing-library

0
推荐指数
1
解决办法
5322
查看次数

如何使用 axios 创建补丁请求

axios.post('/api/v1/users',
            { "edited_field": "email", "email": email },
            { headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': crsfToken }, }
        ).then((response) => {
            // Code
        }).catch((error) => {
            // Code
        })
Run Code Online (Sandbox Code Playgroud)

我有这个 post 方法,但我想创建一个 patch 方法。我见过一些解决方案,他们发布一个带有输入值=“补丁”的表单,但由于我没有使用表单,所以我不知道必须如何完成。

欢迎任何帮助:D

提前致谢!

javascript axios

0
推荐指数
1
解决办法
2万
查看次数

Node.js axios - 如何使用相同的键将字符串数组作为查询参数传递?

我正在循环一个字符串数组,并希望将这些字符串以 30 个为一组作为查询参数传递到 axios GET 请求中,但我不知道如何正确执行。

const ids = ["1","2", "3", "4", "5"] //最多 10K 条目

我需要的是 30 个 id 作为查询参数,每个请求都具有相同的键,如下所示

axios.get("/endpoint?id=1&id=2&id=3&id=4") 等等。我的方法不起作用,我欢迎一些有关如何正确处理此问题的提示。

我拥有的

 const assets = await getRepository(Asset).find({ collection: collection })
      
      const token_ids = assets.map(a => {
        return a.token_id
      })

      const asset_count = assets.length;

      let config: AxiosRequestConfig = {
        headers: this.header,
        params: {
          limit: 50,
          offset: 0,
          side: 1,
          sale_kind: 0,
          order_by: "eth_price",
          order_direction: "asc",
          asset_contract_address: assets[0].asset_contract.address
        }
      }

      while (true) {
        const ids = token_ids.splice(0,30);   //get 30 ids …
Run Code Online (Sandbox Code Playgroud)

node.js axios

0
推荐指数
1
解决办法
2888
查看次数

React应用程序重新渲染并使用axios无限获取数据

我是一名自学成才的开发人员,几乎完全使用原生 iOS 应用程序。对于我的一个项目,我聘请了一名 Web 开发人员来构建 React Web 应用程序(由 Firebase 托管)。他来自乌克兰,突然不得不停下来,所以我接手来完成它。因此,我无法以传统方式学习 React/HTTPS/axios/Node.js,即通过教程、练习、核心概念等缓慢学习。尽管几个月前,我还是能够完成它,一切都很好。然而,在过去的几周里,我不得不重构我的整个架构,包括创建一个新的 GCP 项目、一个新的 Firebase 项目、新的 git 存储库等,其中包括除了一些代码优化和数据模型之外的所有重新配置调整。正是在这次重组的某个时刻,我的问题出现了。我提到这一切是为了指出A)我一直严重依赖他的原创工作,尤其是在设置 Firebase Hosting 方面,B)我不太确定问题出在哪里。我 90% 确定它是用 React 实现的,但这很奇怪,因为从两个月前完成它开始,我并没有真正对异步网络调用进行任何更改,而且它按预期工作。

无论如何,在出现时,Web 应用程序请求向客户端呈现哪个视图,该视图是NotFoundView、 aReviewUserViewUserProfileView,由给定 a 的后端确定userId。问题是当UserProfileView显示时,某些原因会导致该视图无限地重新渲染。首先,在不超过两秒的时间内,它会正确显示此视图,然后非常快速地重置和重新渲染。useEffect我认为它与和/或React 钩子有关useState,尽管我不确定在哪个视图中。

非常感谢任何帮助,谢谢。

export enum ViewState { 
    UserProfile = 'UserProfile',
    ReviewForm = 'ReviewForm',
    NotFound = 'NotFound'
}

....................................................

export class ApiHandler { 
    // Returns a ViewState enum case for main view routing
    public static …
Run Code Online (Sandbox Code Playgroud)

async-await reactjs firebase-hosting axios react-hooks

0
推荐指数
1
解决办法
933
查看次数

axios 返回承诺而不是数据

我正在使用 axios 从 IPFS 查询一些数据,问题是调用特定 api 后返回值是来自 axios 的承诺。

const getNFTDetail = async (url: string) => {
    const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
    try {
      return await axios.get(urlIPF).then((res) => {
        return res.data;
      });
    } catch (error) {
      console.log(error);
    }
  };
Run Code Online (Sandbox Code Playgroud)

我得到的回应:

在此输入图像描述

有没有办法等到承诺得到解决?,正如你所看到的,我已经在函数调用上使用了 async wait 。

reactjs axios

0
推荐指数
1
解决办法
4565
查看次数

设置数据时.map不是React中的函数错误

我正在学习反应并有以下观察。

我无法理解错误背后的原因。

我有下面的代码 -

反应:

useEffect(()=>{
    console.log()
    axios.get('http://localhost:8000/api/records/').then((data) => {console.log('server returned ... ',typeof(data));setRecords(data)}
    ).catch( e => console.log(e))
    
},[])

 const [records,setRecords] = useState([]);
Run Code Online (Sandbox Code Playgroud)
  1. 当仅data在侧面使用时then clause in axios,我收到以下错误,Uncaught TypeError: records.map is not a function

  2. 但是,当我更改如下代码时 - 请注意{data}而不是仅仅data,上述错误得到解决。

    axios.get('http://localhost:8000/api/records/').then(({data}) => {...}

有人可以解释一下上述行为吗?

我尝试打印type of variable data,但在这两种情况下它都是object

{data}为什么当使用 代替时上述错误消失了{data}

表达:

const express = require('express')
const app = express()
var cors = require('cors')
const port = 8000
app.use(cors())


const Records = …
Run Code Online (Sandbox Code Playgroud)

reactjs axios

0
推荐指数
1
解决办法
40
查看次数

错误:使用 nextjs getserversideprops 连接 ECONNREFUSED ::1:5000

我正在尝试连接到 localhost:5000 上的 api,当从邮递员或浏览器调用时它可以完美工作,但在 nextjs getserverside props 中调用时不起作用:

mport { useEffect,useState } from "react";
 import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
 import Axios, {AxiosResponse} from 'axios'
interface Data{
    labels: string[],
    series:number[][]
}
function Chart(props) {
const [data,setData]= useState<Data>()
    useEffect(()=>{
        console.log(props)
 let fetchedData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
    series: [
     [6,5,3,2,1]
    ]
  }
  
  setData(fetchedData)
    },[])
    
      
       new Chartist.Line('.ct-chart', data);
      useEffect(() => {
        setTimeout(() => {
          /* do stuff */
        }, );
      }, []);
    return (
        <>
        <div className="ibox …
Run Code Online (Sandbox Code Playgroud)

typescript axios next.js

0
推荐指数
1
解决办法
2358
查看次数

当 URL 在 ReactJS + Rails 上具有动态参数时,axios 使用错误的 URL

因此,我使用 axios 将我的reactJS 前端与我的rails API 后端链接起来。

这是我的路由器:

[...]
<Route path="/" component={LandingPage} exact={true}/>
<Route path="/meals" component={MealsPage} exact={true}/>
<Route exact path="/user/:token"
                      render={routeProps => (
                        <MyAccountPage {...routeProps} currentUser={this.state} />
                      )}
              />
[...]
Run Code Online (Sandbox Code Playgroud)

这是我使用 axios 的函数:

getCurrentUser: jwt => {
    let config = {
      headers: {}
    }
    if (jwt) {
      config['headers']['Authorization'] = 'Bearer ' + jwt
    }
    return axios.get('api/v1/users/current', config)
      .then(response => {
        console.log(response)
        return response.data
      })
      .catch(error => {
        if( error.response ){
            console.log(error: error.response.data);
        }
        return undefined
      })
  }
Run Code Online (Sandbox Code Playgroud)

/它与和路线完美配合/meals。但是,当 …

ruby-on-rails reactjs axios

-1
推荐指数
1
解决办法
1530
查看次数

在VueJS中使用Axios - 这是未定义的

使用typescript和vuejs + axios,我在post请求上有以下.catch函数 - 我试图捕获一些网络错误并向最终用户报告状态:

      .catch(function(error) {
          console.error(error.response);
          if ( error.message === "Network Error" ) {
              this.alert.show = 1;
              this.alert.message = error.message + ': Please try again later';
          }
      });
Run Code Online (Sandbox Code Playgroud)

this.alert.show在调试器中抛出"this"undefined.这是一般的javascript/typescript和异常处理程序的问题,或者这是Axios中的错误还是我找不到文档的设计决策?

有没有一种方法可以让我在没有"这个"参考的情况下将其传达给我的组件?

完整块:

export default {
  data() {
    return {
      form: {
        email: '',
        password: '',
      },
      alert: {
          show: 0,
          message: '',
      },
    };
  },
  methods: {
    onSubmit(evt) {
      evt.preventDefault();

      if (this.form.password.length > 0) {
          // TODO: Hideous workaround for .catch().
          let that = this;
          this.$http.post('http://localhost:3000/login', {
              email: this.form.email, …
Run Code Online (Sandbox Code Playgroud)

javascript typescript vue.js axios

-1
推荐指数
2
解决办法
744
查看次数

React Hook useEffect 缺少依赖项:'props.match.params.id'

我已经创建了一个 React 应用程序。对于数据获取,我使用了 axios。我的应用程序按预期工作正常。但是在我的终端中,我收到了这样的警告Line 34:6: React Hook useEffect has a missing dependency: 'props.match.params.id'. Either include it or remove the dependency array react-hooks/exhaustive-deps。我不想使用// eslint-disable-next-line react-hooks/exhaustive-deps. 有什么替代解决方案吗?

  useEffect(() => {
    axios
      .get("http://localhost:5000/students/" + props.match.params.id)
      .then(response => {
        setState({
          name: response.data.name,
          birthday: response.data.birthday,
          address: response.data.address,
          zipcode: response.data.zipcode,
          city: response.data.city,
          phone: response.data.phone,
          email: response.data.email
        });
      })
      .catch(function(error) {
        console.log(error);
      });

  }, []);
Run Code Online (Sandbox Code Playgroud)

axios react-hooks use-effect

-1
推荐指数
1
解决办法
899
查看次数

将 JSON 转换为不带键的数组

我有一个查询从数据库返回一列,该列返回以下结果:

[
{
    "tenantName": "H&M"
},
{
    "tenantName": "McDonalds"
}
]
Run Code Online (Sandbox Code Playgroud)

但是,我想使用结果创建一个仅包含名称的数组:[“H&M”,“McDonalds”]

javascript sequelize.js reactjs axios

-2
推荐指数
1
解决办法
785
查看次数