【问题标题】:axios.post returns bad request of 400 React Nativeaxios.post 返回 400 React Native 的错误请求
【发布时间】:2020-03-30 05:38:54
【问题描述】:

我从 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 - node_modules\axios\lib\core\createError.js:16:24 in createError - node_modules\axios\lib\core\settle.js:18:6 在解决 - ... 来自框架内部的另外 10 个堆栈帧

【问题讨论】:

  • 您需要检查服务器上的日志以查看 400 的原因并修复它。仅使用前端代码,我们将无法判断服务器需要什么。
  • @Zaln KhAn 你一定得到了一些响应错误。检查一下,因为您遇到的错误是我们无法使用此代码找到的。
  • axios 文档说以不同的方式发送www-form-urlencoded 的参数。你在追吗?? github.com/axios/…
  • 更新了请查收。
  • 默认情况下,你发送的参数会被解析为json。要将其发送至www-form-urlencoded,您需要按照文档进行操作。

标签: reactjs react-native axios expo


【解决方案1】:

使用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))

【讨论】:

    【解决方案2】:

    尝试使用 fetch 代替,可能是 axios 的一些 bug,你不需要添加任何库,这里是一个例子:

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

    【讨论】:

    • 我可以在 react native expo 应用程序中使用 fetch 获取数据吗?
    • 你知道发生了什么吗?
    【解决方案3】:

    首先从urlhttps://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);
        }
    }
    

    下面给出了使用 get 和 post 服务的示例代码

    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的参考 如果您有任何疑问,请随时了解

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 您的 api 期望是什么? json 还是 FromData?
      • 我正在获取 JSON 格式的数据
      猜你喜欢
      • 2018-03-28
      • 2020-01-15
      • 2019-07-28
      • 2019-07-11
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多