簡體   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