提问者:小点点

第二次axios api调用时GET错误400错误请求


我正在尝试使用Axios从API获取数据。我有两个API调用。第一个调用运行良好,我得到了我期望的数据。然而,第二个返回了400错误错误错误请求。

我已经搜索了多个论坛试图找到解决方案,但我不太理解我找到的代码。

    const [player, setPlayer] = useState([]);
    const [newPlayer, setNewPlayer] = useState([]);

    const FindLoadout = async () => {
        await axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchidsbyqueueJson/${devId}/${generateSignature('getmatchidsbyqueue')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/428/${moment.utc().format('YYYYMMDD')}/-1,00`).then((response) => {
                const playerData = response.data;
                playerData.map((el) => {
                    player.push(el.Match)
                })
                console.log(player);
                for(let i = 0; i < 50; i++) {
                    newPlayer.push(player[i]);
                }
                console.log(newPlayer);
            }).catch((error) => {
                console.log(error);
            });
            axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchdetailsbatchJson/${devId}/${generateSignature('getmatchdetailsbatch')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/${newPlayer.join(",")}`).then((response) => {
                console.log(response);
            }).catch((error) => {
                console.log(error);
            });
    }

错误消息是:

错误:请求失败,状态码为400,位于XMLHttpRequest. handleLoad(xhr.js:60)结算(settle.js:19)处的createError(createError.js:17)


共3个答案

匿名用户

我不知道它是否能准确解决您的问题,但是当使用async/await进行数据获取时,一种常见的做法是这样做:

const FindLoadout = async () => {

  const playerData= await axios
    .get(`http://api.paladins.com/player/154`)
    .then(response => response.data);

  const gameData= await axios
    .get(`http://api.paladins.com/game/788`)
    .then(response => response.data);

  return {player: playerData, game: gamedata}
}

也就是说,您将API调用获取的数据分配给变量,然后从变量中返回您需要的数据(在您认为必要的任何操作之后)。

以这种同步语法编写异步代码的能力是async/await最吸引人的特性之一。

我怀疑您收到的错误是因为您的第二次调用在触发之前没有await关键字。

编辑:正如其他人所说,你肯定会遇到错误使用钩子的问题,但这不是问题的范围。

匿名用户

首先,您将异步和传统promise混合在一起

[编辑:您也直接改变状态而不是使用setState]

[EDIT2:设置状态不是立即的,因此直接在setState之后的控制台. log的状态(以及axios获取依赖于状态值的请求)通常不会记录您预期的值,因此应该包含在状态更新时传递给setState-or-利用useEffect的回调函数中]

[EDIT3:在循环之外构建新状态,然后在之后设置状态]

const [player, setPlayer] = useState([]);
const [newPlayer, setNewPlayer] = useState([]);
const FindLoadout = async () => {
    useEffect(()=>{
        if (!player.length) return
        const newState = [...newPlayer]
        for(let i = 0; i < 50; i++) {
            newState.push(player[i]);
        }
        setNewPlayer(newState)
    }, [player]);
    useEffect(() => {
        if (!newPlayer.length) return 
         axios
            .get(`http://api.paladins.com/paladinsapi.svc/getmatchdetailsbatchJson/${devId}/${generateSignature('getmatchdetailsbatch')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/${newPlayer.join(",")}`)
            .then((gameData)=>{
                console.log(gameData)
            }).catch((error)=>{
                console.error(error)
            })
    }, [newPlayer]);
    try {
        const playerData= await axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchidsbyqueueJson/${devId}/${generateSignature('getmatchidsbyqueue')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/428/${moment.utc().format('YYYYMMDD')}/-1,00`)
        const newState = [...player]
        playerData.map((el) => newState.push(el.Match))
        setPlayer(newState)
    }catch(error) {
        console.error(error);
    } 
}

如果你想第二次使用asyc,你也可以使用回调来代替:https://dev.to/n1ru4l/homebrew-react-hooks-useasynceffect-or-how-to-handle-async-operations-with-useeffect-1fa8

useEffect(() => {
        if (!newPlayer.length) return
        const myCallback = async ()=>{
            try{
                const gameData = await axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchdetailsbatchJson/${devId}/${generateSignature('getmatchdetailsbatch')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/${newPlayer.join(",")}`)
                console.log(gameData)
            }catch(error){
                console.error(error)
            }
        }
        myCallback()
}, [newPlayer]);

如果这不能解决问题:

400错误请求错误是一个HTTP状态代码,这意味着您发送到网站服务器的请求不知何故不正确或损坏,服务器无法理解它。

IE:你的URL不正确,API调用我将仔细检查"GenerateSignature"函数是否返回正确的值。如果是这种情况,我会检查以确保newPlayer. join(",")返回正确的值。

匿名用户

我认为问题在于您如何为playernewPlayer赋值。由于您使用的是useState挂钩,因此应该使用setPlayersetNewPlayer

你能告诉我在第二次api调用之前newPlayer的值是什么吗?

也许你可以像这样更新它:

const FindLoadout = async () => {
        await axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchidsbyqueueJson/${devId}/${generateSignature('getmatchidsbyqueue')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/428/${moment.utc().format('YYYYMMDD')}/-1,00`).then((response) => {
                const playerData = response.data;
                //playerData.map((el) => {
                //    player.push(el.Match)
                //})
                setPlayer(playerData.map(el) => el.Match);
                console.log(player);
                //for(let i = 0; i < 50; i++) {
                //    newPlayer.push(player[i]);
                //}
                // I'm not sure how to update this assignment
                console.log(newPlayer);
            }).catch((error) => {
                console.log(error);
            });
            axios.get(`http://api.paladins.com/paladinsapi.svc/getmatchdetailsbatchJson/${devId}/${generateSignature('getmatchdetailsbatch')}/${props.sess}/${moment.utc().format('YYYYMMDDHHmmss')}/${newPlayer.join(",")}`).then((response) => {
                console.log(response);
            }).catch((error) => {
                console.log(error);
            });
    }