POST-запрос пуст - PullRequest
       13

POST-запрос пуст

1 голос
/ 04 апреля 2020

Я пытаюсь отправить значения формы в БД (используйте redux-thunk, express и MongoDB). Мой компонент выглядит как

const AddPerson = (props) => {
  const [person, setPerson] = useState({
    name: '',
    age: '',
    status: ''

  })

  const handleChange = (event) => {
    setPerson({
      ...person,
      [event.target.name]: event.target.value
    })
  }

  const handleSubmit = (event) => {
    props.putCustomersData({ person })
    // eslint-disable-next-line no-console
    console.log(person)
    event.preventDefault()
  }
  return (
    <div>
      <Head title="This is new person" />
      <form onSubmit={
        handleSubmit
        }
      >
        <div>
          <div>name</div>
          <input
            name="name"
            type="text"
            value={person.name}
            onChange={handleChange}
          />
          <div>age</div>
          <input
            type="text"
            name="age"
            value={person.age}
            onChange={handleChange}
          />
          <div>status</div>
          <input
            name="status"
            type="text"
            value={person.status}
            onChange={handleChange}
          />
          <div>
            <button type="submit">Ok</button>
          </div>
        </div>
      </form>
    </div>
  );
}


AddPerson.propTypes = {}

AddPerson.defaultProps = {
  person: { }
}

const mapStateToProps = state => ({
  persons: state.persons.data
})

const mapDispatchToProps = dispatch => bindActionCreators({ putCustomersData }, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(AddPerson)

и приставка

const initialState = {
  data: []
}


export default (state = initialState, action) => {
  switch (action.type) {
    case POST_CUSTOMER:
      return {
        ...state,
        data: action.data
      }
    default:
      return state
  }
}

export function putCustomersData(person) {
  return (dispatch) => {
    axios.post('someUrl', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: { person }
    })
      .then((responce) => {
        dispatch({ 
        type: POST_CUSTOMER, 
        data: responce.data 
        })
        // eslint-disable-next-line no-console
        console.log('ok', responce.data)
      })
      .catch((error) => {
        dispatch({ type: POST_CUSTOMER_ERROR, error })
        // eslint-disable-next-line no-console
        console.log('err', error)
      })
  }
}

И мой запрос пишет в БД как пустой. console.log(person) показать правильный объект в консоли:

 {name: "Anna", age: "14", status: "student"}

Но console.log(responce.data) показывает только

  {_id: "5e888cb9ca6e5518a5bdf0c2", __v: 0}

Я проверяю свои запросы с почтальоном, и они работают. Я не понимаю, где моя проблема. Почему объект не пишет в БД?

1 Ответ

0 голосов
/ 04 апреля 2020

Параметры вашего вызова axios.post(...) находятся в неправильном порядке. У вас есть:

  axios.post('someUrl', {
      headers: {
        'Content-Type': 'application/json',
      },
      body: { person }
    })

Правильный порядок:

axios.post('someUrl', {
  { person },
  headers: {
    'Content-Type': 'application/json',
  }  
})

Из документов

ax ios .post (url [, data [, config]])

...