【问题标题】:react axios 401 unauthorized and sometimes 403反应 axios 401 未经授权,有时 403
【发布时间】:2020-02-21 17:54:13
【问题描述】:

我正在构建一个请求 laravel php api 的反应原生应用程序帖子。它适用于邮递员,但不适用于 Axios。你知道我该如何解决吗?我无法发布表单数据

我尝试了其他形式发送 Axios 的 post 请求。但它们都不是解决方案

axios({
            method: 'post',
            url: 'URL',
            params: {
                "api_token": token,
                "name": "talha"
            },
            headers: {
                Accept: 'application/json',
                'Content-Type': 'multipart/form-data'
            }
        }).then(response => alert(response)).catch(err => console.warn(err))


-----
const serverURL = "URL";

const http = axios.create({
    timeout: 1000,
    baseURL: serverURL,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    withCredentials: false,
    cache: false,
    dataType: "jsonp"
});

data is a formdata

await http.post("/passengers", data, config)
            .then(Response => alert(Response.data))
            .catch(error => console.warn("hata", error))
-----
axios.post( 'URL',
                    data,
                    {
                      headers: {
                          Accept: 'application/json',
                          'Content-Type': 'multipart/form-data'
                      }
                    }
                  ).then(function(){
                    alert('SUCCESS!!');
                  })
                  .catch(function(){
                    alert('FAILURE!!');
                  });

邮递员脚本:

https://pastebin.ubuntu.com/p/vS54dytpCQ/

【问题讨论】:

  • 你能发布邮递员脚本吗?
  • 不。我得到同样的错误 401
  • 让它在邮递员中工作并提供详细信息
  • 向 api 发送一些参数和标头。我已经将它们添加到代码中。但我给出了 401 错误
  • 请生成可以工作的邮递员脚本并在此处发布

标签: laravel react-native networking axios


【解决方案1】:

您可以使用我的 API 帮助函数进行连击开发。

import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

const api = async (url, method, body) => {
  /**
   * config object for fetch
   */
  const config = {
    method: 'get',
    baseURL: 'BASEURL WILL BE HERE',
    url,
    headers: {
      'Content-type': 'application/json',
      authorization: await AsyncStorage.getItem('auth_token'),
    },
  };

  if (method) {
    config.method = method;
  }
  if (body) {
    config.data = body;
  }

  let response;
  try {
    response = await axios(config);
    return {...response.data};
  } catch (e) {
    throw new Error(e.message);
  }
};

export default api;

那就用这个函数

import api from 'filpath';

const functionName = async () => {
  try{
   const res = await api('/passengers', 'POST' posData);
   console.log(res.data);
  } catch(e){
     alert('FAILURE!!')
  }
}

注意:用户登录时将身份验证令牌保存到 AsyncStorage。

【讨论】:

  • 我试过但还是一样。我发送带有参数而不是标题的 api
  • await api(/passengers?param1=${param1}) 你可以这样用
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 2018-02-23
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 2018-05-19
  • 2020-06-11
相关资源
最近更新 更多