【问题标题】:axios post dosent send any data to djangoaxios post 不向 django 发送任何数据
【发布时间】:2020-05-12 17:10:20
【问题描述】:

我在 pythonanywhere 上使用 react-native 作为前端,使用 django 作为后端。 我的前端代码:

  axios({
    method: 'POST',
    url: 'http://mohammadss.pythonanywhere.com/login',
    // url: '127.0.0.1:8000/login',
    headers: {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    data: qs.stringify({
      Hello: 'Hello?',
    }),
  })
    .then(res => {
      console.log(res.data);
    })
    .catch(res => {
      console.log(res);
    });

和我的后端代码:

def Login(request):
res = request.POST ;
return JsonResponse(res , JSONEncoder)

但它不会返回任何东西。有了邮递员,一切都很好。并且使用 fetch() 函数我可以看到结果:

fetch('http://mohammadss.pythonanywhere.com/login/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: qs.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
}).then(reponse => {
  reponse.json().then(RES => {
    console.log(RES);
  });
});

但是 axios 没用。

【问题讨论】:

  • console.log 中出现什么错误?
  • 您可能面临CORS 错误。你的CORS 是否在你的 django 设置中正确配置?

标签: django react-native axios fetch


【解决方案1】:

我找到了自己的路。我做的事情: 1- 在我的 Pythonanywhere 主机上安装 [[django-cors-headers 3.2.1]1]1。感谢尼玛。 (当然我不知道这是否有必要!)。

2- 我将代码更改为:

const data = new FormData();
data.append('username', 'myname');
data.append('password', 'blablabla');

axios
  .post('http://mohammadss.pythonanywhere.com/login/', data, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
  .then(function(response) {
    console.log(typeof response.data.Code);
    if (response.data.Code == '1') {
      alert('Loged IN');
    }
  })
  .catch(function(error) {
    console.log(error);
  });

我不知道我的代码有多干净,但对我有用!

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2020-06-18
    • 2021-11-13
    • 1970-01-01
    • 2021-02-21
    • 2019-06-20
    • 1970-01-01
    • 2019-09-05
    • 2020-06-05
    相关资源
    最近更新 更多