我如何从axson获得json的响应数据

时间:2017-12-12 08:34:15

标签: reactjs django-rest-framework

我如何通过axios从json获得响应数据和状态标题?

我的axios代码有什么问题?

我的构造函数:

class DetailProduct extends React.Component{

    constructor(){
        super();
        this.state = {
          dataOperations: [],
        isLoading: true
        };
      console.log(this.state.idf)

    axios.post('http://127.0.0.1:8000/barang/select/', { id: 1 })
    .then(function(response){
      console.log(response.data)
      console.log(response.status)
    });  
    }

我的Django休息框架:

class Selectitem(GenericAPIView):

    permission_classes = []

    def post(self, request):

        getb = Barang.objects.filter(pk = request.POST.get('id'))
        if getb.exists():
            f = getb.first()
            return Response({'nama_barang': f.nm_barang, 'harga_satuan': f.harga_satuan}, status=status.HTTP_200_OK)
        else:
            return Response({"message": "What you were looking for isn't here."}, status=status.HTTP_400_BAD_REQUEST)
    def get_serializer_class(self):
        return SelectItem

如果使用邮递员,我可以获得数据

postman response data and status

1 个答案:

答案 0 :(得分:0)

尝试这样做

const URL = `SOME_API_URL_THAT_YOU_TYPE_HERE`;
return axios({
  method: 'POST',
  url: URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${YOUR_TOKEN}`
  },
  data: {
    payload1: 'lorem',
    payload2: 'ipsum'
  },
})
.then(res => {
  console.log('Data', res.data);
 })
.catch(error => {
  console.log('Error', error.response.data);
 })