繁体   English   中英

在第二个 axios api 调用上获取错误 400 错误请求

[英]GET error 400 bad request on second axios api call

我正在尝试使用 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);
            });
    }

错误信息是:

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

我不知道它是否能完全解决您的问题,但是当使用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关键字。

编辑:另外,正如其他人所说,你肯定会遇到不正确使用钩子的问题,但这不是问题的 scope。

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

[编辑:您还直接改变 state 而不是使用 setState]

[EDIT2: setting state is not immediate therefor a console.log of state (and the axios get request relying on the state value) directly after a setState will not usually log the value you anticipate and therefore should be included inside the callback function passed to setState - 或 - 当 state 更新时使用 useEffect]

[EDIT3:在循环之外构建新的 state 然后在 setState 之后]

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);
    } 
}

如果您想在第二个 useEffect 中坚持使用 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 Bad Request 错误是一个 HTTP 状态代码,这意味着您发送到网站服务器的请求不正确或已损坏,服务器无法理解。

即:您的 URL 对于 API 调用不正确 我会仔细检查“generateSignature” function 是否返回正确的值。 如果是这种情况,我会检查以确保 newPlayer.join(",") 返回正确的值。

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

你能告诉我在第二次newPlayer调用之前 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); }); }

关于更新newPlayer :由于状态是异步更新的,所以当您尝试使用player中的值更新newPlayer时, player中没有任何内容。

尝试使用一些硬编码值发出请求,以查看问题是否出在 api 请求或变量中的值上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM