axios.post返回400 React Native的错误请求

时间:2019-12-05 10:04:29

标签: reactjs react-native axios expo

我正在从API获取令牌,但是很不幸,我的API返回了400个错误的请求。我已经通过Postman检查了我的api,并且在那儿工作正常。请让我知道解决方案或任何错误。

async componentWillMount(){
 axios.post('http://api.myapiurl.com/token', {
                grant_type: 'PASSWORD',
                username: 'MY_USERNAME',
                password: 'MY_PASSWORD'
            }, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).then(response => {
                console.log(response.data)
            }).catch(err => console.log("api Erorr: ", err.message))
}

以下回应错误

  

请求失败,状态码为400   -createError中的node_modules \ axios \ lib \ core \ createError.js:16:24   -在结算中使用node_modules \ axios \ lib \ core \ settle.js:18:6   -... 10个来自框架内部的堆栈框架

Postman Screenshot

4 个答案:

答案 0 :(得分:1)

尝试使用fetch代替,可能是一些axios错误,您不需要添加任何库,这是一个示例:

fetch("http://api.myapiurl.com/token", {
  method: "POST", // *GET, POST, PUT, DELETE, etc.
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    grant_type: "PASSWORD",
    username: "MY_USERNAME",
    password: "MY_PASSWORD"
  }) 
})
  .then(res => {
    res.json();
  })
  .then(data => console.log(data))  // ur data is here
  .catch(err => console.log("api Erorr: ", err));

答案 1 :(得分:0)

据我所知,您正在发送json数据,但是您的Content-Type标头设置为application/x-www-form-urlencoded; charset=UTF-8。如果您的api需要json,则应为application/json

答案 2 :(得分:0)

首先从URL https://www.npmjs.com/package/react-native-axios安装软件包axios 然后创建两个用于处理get和post请求的服务,以便您可以重用它们

GetService.js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const GetService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.get(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}    

PostService.js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {

    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const PostService = (data,Path,jwtKey) => {
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.post(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}

下面给出了使用获取和发布服务的示例代码

import { PostService } from './PostService';
import { GetService } from './GetService';


let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });

let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});



GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
    // resp.data will contain json data from server
}).catch(err => {
    // handle error here
});

来自我另一则帖子Post action API with object parameter within the URL的参考 如果您有任何疑问,请随时了解

答案 3 :(得分:0)

使用QueryString.stringify()可解决此问题。我只是将尸体传递到QueryString.stringify()中,如下所示:

axios.post('http://api.apiurl.com/token', QueryString.stringify({
            grant_type: 'MY_GRANT_TYPE',
            username: 'MY_USERNAME',
            password: 'MY_PASSWORD'
        }), {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }).then(response => {
            console.log(response.data)
        }).catch(err => console.log("api Erorr: ", err.response))