Django:使用reactJS发送请求时出现错误请求

时间:2021-03-30 07:00:05

标签: django

我在后端使用 django-rest-framework,我正在尝试从 React 前端发布以下数据。

handleSubmit() {
   fetch('http://127.0.0.1:8000/api/debt/create',{
       method: 'POST',
       headers: {
           Authorization: `Bearer ${localStorage.getItem('id_token')}`,
           'Content-Type': 'application/json'
       },
       body: JSON.stringify({
           user: '1',
           customer: '9',
           debtKey: 'b1d9ef1b-45ad-4dc5-80cc-95f7994c0aae',
           createduserKey: '0245abb9-2837-4f37-ae02-9be1b88887ef',
           totalDebt: 789,
           receivedAmount: 115,
           description: 'Debt description',
           paymentDate: '01.01.2019'
       }),
   }).then(response => {
       console.log(response);
       return response.json()
   }).then(json => {
       //this.setState({
       //    user:json
       //});
   });
 console.log("Form Sumbmssion");
}

但是我收到了 "BAD REQUEST" 错误。我缺少什么?谢谢

2 个答案:

答案 0 :(得分:2)

我认为您只需要在 http://127.0.0.1:8000/api/debt/create 末尾添加“/”即可。 错误的请求通常仅由该问题引起。但是你为什么要使用 fetch 呢。如果您在前端使用 React.js,请考虑使用 axios。它与 fetchAPI 相同,但更灵活。

答案 1 :(得分:1)

Authorization 是一个键。它应该在 quotes 中。

headers: {
       'Authorization': `Bearer ${localStorage.getItem('id_token')}`,
       'Content-Type': 'application/json'
   },