Axios PUT / PATCH但不包含任何身体

时间:2017-12-22 03:08:28

标签: reactjs axios

我成功将json发布到后端。但我遇到patch的问题。我已关注docs我也试过了axios.patch()。没有错误PATCH到达Django,但没有数据。

Quesion:
我想念哪里?

import axios from "axios/index";
import {takeEvery, call, put} from "redux-saga/effects";
import {getAuthToken, prepareJWTHeader} from "../../login/utils";
import {ROOT_URL, SELECT_COMPANY, SELECT_COMPANY_COMPLETE, SELECT_COMPANY_FAILED} from "../../constants";

const shootSelectedCompany = (companyId) => {
  const token = getAuthToken();
  const jwt = prepareJWTHeader(token);
  let request = axios.create({
    method: 'PATCH',
    baseURL: `${ROOT_URL}/api/userprofiles/select_company/`,
    headers: {
      Authorization: jwt,
      'Content-Type': 'application/json'
      // Also had tried https://github.com/axios/axios/issues/97
      'Content-Type' : 'application/x-www-form-urlencoded'
    }
    data: {
       selected_company: companyId
    }
    //Also had tried
    //body: {
    //   selected_company: companyId
    //}
  });
  return request.patch(null);
};


function* patchSelectedCompany(action) {
  try {
    const res = yield call(shootSelectedCompany, action.payload);
    yield put({
      type: SELECT_COMPANY_COMPLETE,
      payload: res
    });
  } catch (err) {
    yield put({
      type: SELECT_COMPANY_FAILED,
      payload: err
    });
  }
}

export function* watchSelectCompany() {
  yield takeEvery(SELECT_COMPANY, patchSelectedCompany)
}

package.json

{
  "name": "f2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "0.17.1",
    "history": "^4.7.2",
    "lodash": "^4.17.4",
    "querystring": "^0.2.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "react-scripts": "^1.0.17",
    "redux": "^3.7.2",
    "redux-form": "^7.2.0",
    "redux-promise": "^0.5.3",
    "redux-saga": "^0.16.0",
    "redux-thunk": "^2.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Django

@list_route(methods=['patch'], permission_classes=[IsAuthenticated,])
def select_company(self, request):
    try:
        profile = UserProfile.objects.get(user=request.user)
        valid_companies = self.request.user.userprofile.companies.all()
        selected_company = Company.objects.get(
            id=request.data.get('selected_company')[0]
        )
        if selected_company in valid_companies:
            profile.selected_company = selected_company
            profile.save()
        else:
            logger.warning(
                f"{request.user} submits an invalid company_id: {request.data.get('selected_company')[0]}"
            )
            return Response(f'{request.user} submits an invalid companyID. Your action has been log!',
                            status=status.HTTP_409_CONFLICT)
    except TypeError:
        return Response({'detail': f'{request.user} submit a blank company'}, status=status.HTTP_400_BAD_REQUEST);
    except Company.DoesNotExist:
        # request.user PATCH with non exist company_id
        return Response({'detail': f'{request.user} select an invalid company'}, status=status.HTTP_406_NOT_ACCEPTABLE)
    except UserProfile.DoesNotExist:
        return Response({'detail': f'{request.user} has no userprofile'}, status=status.HTTP_404_NOT_FOUND)
    return Response({"detail": f'{profile.selected_company.name} has been selected'}, status=status.HTTP_202_ACCEPTED)

供参考:
我已将pdb放入TypeError。这是一个证据。

(Pdb) request.data
{}

requirements.txt

djangorestframework==3.7.3
django==1.11.7

2 个答案:

答案 0 :(得分:0)

在那里的文档上查看transformRequest。以下链接包含其他人的样本。

https://github.com/axios/axios/issues/97

答案 1 :(得分:0)

我必须拆分data并将url作为null。我虽然axios可能更方便。

  let request = axios.create({
    method: 'PATCH',
    baseURL: `${ROOT_URL}/api/userprofiles/select_company/`,
    headers: {
      Authorization: jwt,
      'Content-Type': 'application/json'
    },
  });
  return request.patch(null, {
    selected_company: companyId
  });