繁体   English   中英

axios 获取请求返回请求失败,错误 400

[英]axios get request return request failed with error 400

我需要帮助解决这个问题。 我是 React Native 和 javascript 的新手。 现在我正在尝试将 React Native 应用程序与 API 连接起来。 这个过程要求我先通过axios.post获取令牌,然后才能使用axios.get获取数据。

长话短说,下面是我的代码片段。

... // code 
const TOKEN_URL = 'https://test.co/testing/tokens'
const DATA_URL = 'https://test.co/testing/data/page1'

const getToken = () => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

//'export' here is for use in other code: example onPress function
export const fetchDriver = () => {
    const config = {
        headers: {
            'Bearer': getToken()
        }
    };

    axios.get(DRIVER_URL, config)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });            
};

我预期的控制台日志将是这样的

{
    "timestamp": 1510038433,
    "verb": "GET",
    "object": "student",
    "data": {
        "age": "12",
        "id": "90000",
        "name": "Test Student",
        "emergencyName": "asd",
        "createdAt": "2017-10-04T05:39:39+00:00"
    }
}

但是我不断收到错误消息,说Request failed with status code 400

我正在使用 Expo 来开发这个应用程序。

错误的详细信息是这样的

- node_modules/axios/lib/core/createError.js:16:24 in createError
- node_modules/axios/lib/core/settle.js:19:6 in settle
- node_modules/axios/lib/adapters/xhr.js:78:13 in handleLoad
- node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:540:23 in 
setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:381:25 in 
__didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:182:12 in 
emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:306:47 in 
__callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:26 in 
<unknown>
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:269:6 in 
__guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:107:17 in 
callFunctionReturnFlushedQueue

如果错误来自那里,我没有任何编辑 api/server 的授权。

如果我在代码段中遗漏了任何一点,请帮助我。 感谢您的帮助和建议。

旁注,您忘记在 getToken 内返回

我会告诉你为什么会发生这种情况。 Promise 是异步的,您的 axios 调用也是如此。 因此,您需要以某种方式等待第一次调用结果。 否则,如果您放置const a = axiosCall()并尝试立即使用它,则a值将是Pending (而不是字符串)。

为此,您可以使用 promise 或 async/await。 我将向您展示使用 Promise 的正确方法。 我刚刚复制了您的代码并对其进行了一些重构。 还要记住, driver仍然是一个承诺,所以你需要像其他事情一样处理它。

 const getToken = () => { axios.post(TOKEN_URL, { email: 'email', password: 'password', role: 'user' }) .then((response) => { //console.log(response.data.token); return response.data.token; }) .catch((error) => { console.log(error); }); }; //'export' here is for use in other code: example onPress function export const fetchDriver = () => { const config = { headers: { 'Bearer': getToken() } }; axios.get(DRIVER_URL, config) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); };

您没有链接您的请求。 您必须等到获得令牌才能使用它。

像这样的东西

获取令牌

const getToken = () => {
    return axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

获取驱动程序

export const fetchDriver = () => {
  return getToken().then(token => {
    const config = {
      headers: {
        'Bearer': token
      }
    };

    return axios.get(DRIVER_URL, config)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  });
}

您需要等到令牌 api 获得返回响应,然后您需要使用令牌进行第二次 api 调用

像这样改变

getToken :更改为异步函数

const async getToken = () => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

fetchDriver : 在调用 getToken 函数时添加 await

export const fetchDriver = () => {
    const config = {
        headers: {
            'Bearer': await getToken()
        }
    };

    axios.get(DRIVER_URL, config)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });            
};

暂无
暂无

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

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