简体   繁体   English

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

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

I need help on solving this issue.我需要帮助解决这个问题。 I am new with react native and javascript.我是 React Native 和 javascript 的新手。 Now I am trying to hook up the react native application with API.现在我正在尝试将 React Native 应用程序与 API 连接起来。 This process require me to get the token first by axios.post before I can do axios.get to fetch the data.这个过程要求我先通过axios.post获取令牌,然后才能使用axios.get获取数据。

Long story short, below is my code snippet for both.长话短说,下面是我的代码片段。

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

My expected console log would be something like this我预期的控制台日志将是这样的

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

But I keep getting error saying Request failed with status code 400但是我不断收到错误消息,说Request failed with status code 400

I am using Expo to develop this app.我正在使用 Expo 来开发这个应用程序。

Detail on the error is like this错误的详细信息是这样的

- 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

I do not have any authorization to edit the api/server if the error comes from there.如果错误来自那里,我没有任何编辑 api/server 的授权。

Please help me if there is any point that I have been missing out in the snippet.如果我在代码段中遗漏了任何一点,请帮助我。 Thank you for your help and suggestion.感谢您的帮助和建议。

sidenote, you forgot to return inside getToken旁注,您忘记在 getToken 内返回

I'll just give you back story on why this happens.我会告诉你为什么会发生这种情况。 Promises are asynchronous, so is your axios call. Promise 是异步的,您的 axios 调用也是如此。 Therefore you need to somehow wait for first call result.因此,您需要以某种方式等待第一次调用结果。 Otherwise if you put const a = axiosCall() and try to use it right away the a value would be Pending (not a string tho).否则,如果您放置const a = axiosCall()并尝试立即使用它,则a值将是Pending (而不是字符串)。

For that you can use promises or async/await.为此,您可以使用 promise 或 async/await。 I'll show you proper approach with promises.我将向您展示使用 Promise 的正确方法。 I've just copied your code and refactored it a bit.我刚刚复制了您的代码并对其进行了一些重构。 Also remember that driver is still a promise so you need to handle it as other things.还要记住, 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); }); };

You are not chaining your requests.您没有链接您的请求。 You have to wait till you get the token to be able to use it.您必须等到获得令牌才能使用它。

Something like this像这样的东西

getToken获取令牌

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

fetchDriver获取驱动程序

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

You need to wait until token api get return response and after that You need make second api call with token您需要等到令牌 api 获得返回响应,然后您需要使用令牌进行第二次 api 调用

change like this像这样改变

getToken : change to async function 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 : add await while calling getToken function 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