首页 > 解决方案 > 未捕获(承诺)错误:请求失败,状态码为 400,如何在 React.js + Django App 中解决此错误?

问题描述

我正在使用安装在 django 应用程序中的 Django rest API 和 React.js 前端来编写应用程序。

尝试从响应其余 API 发出发布请求时遇到错误。

发布到 Django rest API 可以在 postman 中使用。我正在尝试使用 useState 挂钩、Redux 和 axios 设置组件。

我不完全确定我正确设置了状态。

这是相关代码:来自表单组件(我怀疑错误在这里):

import React, { useState } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { addLead } from "../../actions/leads";

const Form = ({ addLead }) => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");

  const onSubmit = e => {
    e.preventDefault();
    const lead = { name, email, message };

    addLead(lead);
    // Clear Fields
    setName("");
    setEmail("");
    setMessage("");
  };
  return (
    <div className="card card-body mt-4 mb-4">
      <h2>Add Lead</h2>
      <form onSubmit={onSubmit}>
        <div className="form-group">
          <label>Name</label>
          <input
            className="form-control"
            type="text"
            name="name"
            onChange={e => setName(e.target.value)}
            value={name}
          />
        </div>
        <div className="form-group">
          <label>Email</label>
          <input
            className="form-control"
            type="email"
            name="email"
            onChange={e => setEmail(e.target.value)}
            value={email}
          />
        </div>
        <div className="form-group">
          <label>Message</label>
          <textarea
            className="form-control"
            type="text"
            name="message"
            onChange={e => setMessage(e.target.value)}
            value={message}
          />
        </div>
        <div className="form-group">
          <button type="submit" onClick={onSubmit} className="btn btn-primary">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
};

Form.propTypes = {
  addLead: PropTypes.func.isRequired
};

export default connect(
  null,
  { addLead }
)(Form);

从行动/线索:

// ADD LEAD
export const addLead = lead => dispatch => {
  try {
    axios.post("/api/leads/", lead).then(res => {
      dispatch({
        type: ADD_LEAD,
        payload: res.data
      });
    });
  } catch (err) {
    console.log(err);
  }

从我的减速机:

 case ADD_LEAD:
      return {
        ...state,
        leads: [...state.leads, action.payload]
      };

服务器正在运行而没有错误。表单正在显示并且 onChange 函数正在运行。上面 Form.js 中的 onSubmit 函数会导致该问题。这是错误:

VM348 xhr.js:172 POST http://localhost:8000/api/leads/ 400 (Bad Request)
dispatchXhrRequest @ VM348 xhr.js:172
xhrAdapter @ VM348 xhr.js:11
dispatchRequest @ VM342 dispatchRequest.js:59
Promise.then (async)
request @ VM339 Axios.js:53
Axios.<computed> @ VM339 Axios.js:78
wrap @ VM337 bind.js:9
eval @ VM333 leads.js:44
eval @ VM364 index.js:9
dispatch @ VM280:1
eval @ VM315 redux.js:483
onSubmit @ VM297 Form.js:46
callCallback @ VM290 react-dom.development.js:362
invokeGuardedCallbackDev @ VM290 react-dom.development.js:411
invokeGuardedCallback @ VM290 react-dom.development.js:466
invokeGuardedCallbackAndCatchFirstError @ VM290 react-dom.development.js:480
executeDispatch @ VM290 react-dom.development.js:612
executeDispatchesInOrder @ VM290 react-dom.development.js:637
executeDispatchesAndRelease @ VM290 react-dom.development.js:743
executeDispatchesAndReleaseTopLevel @ VM290 react-dom.development.js:752
forEachAccumulated @ VM290 react-dom.development.js:724
runEventsInBatch @ VM290 react-dom.development.js:769
runExtractedPluginEventsInBatch @ VM290 react-dom.development.js:914
handleTopLevel @ VM290 react-dom.development.js:5848
batchedEventUpdates$1 @ VM290 react-dom.development.js:24343
batchedEventUpdates @ VM290 react-dom.development.js:1463
dispatchEventForPluginEventSystem @ VM290 react-dom.development.js:5943
attemptToDispatchEvent @ VM290 react-dom.development.js:6059
dispatchEvent @ VM290 react-dom.development.js:5963
unstable_runWithPriority @ VM292 scheduler.development.js:815
runWithPriority$2 @ VM290 react-dom.development.js:12188
discreteUpdates$1 @ VM290 react-dom.development.js:24359
discreteUpdates @ VM290 react-dom.development.js:1486
dispatchDiscreteEvent @ VM290 react-dom.development.js:5926
VM350 createError.js:16 Uncaught (in promise) Error: Request failed with status code 400
    at createError (VM350 createError.js:16)
    at settle (VM349 settle.js:17)
    at XMLHttpRequest.handleLoad (VM348 xhr.js:59)

什么可能导致此问题?谢谢。

标签: djangoreactjsreduxaxiosreact-hooks

解决方案


在潜在客户应用程序的 models.py 中,我更改了模型以匹配反应帖子。这是工作模型:

class Lead(models.Model):
  name = models.CharField(max_length=100)
  email = models.EmailField(max_length=100, unique=True)
  message = models.CharField(max_length=500, blank=True)
  created_at = models.DateTimeField(auto_now_add=True)

一旦我改变了这个,我就跑了

python mangage.py makemigrations leads

&

python manage.py migrate

在我的虚拟环境终端中。

问题解决了。


推荐阅读