简体   繁体   English

Axios 发布请求不适用于 Django Rest 框架

[英]Axios post request not working with Django Rest Framework

I am trying to use Axios post to create a user in my Django Rest Framework api.我正在尝试使用 Axios 帖子在我的 Django Rest 框架 Z8A5DA52ED126447D359E7 中创建用户。

Currently getting "Request failed with status code 400" when trying to post.当前在尝试发布时收到“请求失败,状态码为 400”。

It works perfectly fine in postman.它在 postman 中运行良好。

drfServer.js drfServer.js

import axios from 'axios';

export default axios.create({
    baseURL: 'https://example.com'
});

AuthContext.js AuthContext.js

const signup = (dispatch) => async ({ email, password }) => {
    try {
        const response = await drfApi.post('/user/',
            {
                data: {
                    username: email,
                    password: password
                }
            }
        );
        // await AsyncStorage.setItem('token', response.data.token);
        // dispatch({ type: 'signin', payload: response.data.token });
        // navigate('Task')
    } catch (err) {
        console.log(err.message)
        dispatch({ type: 'add_error', payload: 'Something went wrong with sign up' })
    }
};

I tried using fetch and it works.我尝试使用 fetch 并且它有效。 But with Axios I am not getting it right.但是对于 Axios 我没有做对。

Any ideas how to make it work?任何想法如何使它工作?

Can you try this code.你可以试试这个代码。

const signup = ({email,password}) => dispatch => {
    return axios({
        method: "post",
        url: "your api url",
        data: { 
          username: email,
          password
        })
        .then(result => {
          console.log(result.data);
         })
        .catch(error => {
          console.log(error);
         })
};

You can find the axios example code here https://github.com/axios/axios您可以在此处找到 axios 示例代码https://github.com/axios/axios

Maybe you can try this:也许你可以试试这个:

const response = await drfApi.post('/user/', {
                    username: email,
                    password: password
                   }
                 );

As using axios.post will automatically take the 2nd param and make it an object with data key由于使用 axios.post 将自动获取第二个参数并使其成为带有data密钥的 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM