【问题标题】:AXIOS: Can I send more than one Data item to an API in a POST request?AXIOS:我可以在 POST 请求中向 API 发送多个数据项吗?
【发布时间】:2020-11-03 01:15:32
【问题描述】:

所以我有一个收集数据的表单,并使用 myForm = new FormData() 发送到 API。然而,模型中填充的项目之一在 MongoDB 模型中具有多个属性。由于表单必须具有一对一的密钥对关系,因此我无法将其作为对象发送。所以,作为一个解决方案,我在我的控制器中构建对象,我想把它和其他杂项一起发送过来。表单数据(下面代码中的 startLocation 对象)。

具体看下面的代码,我想我可以使用 data: myForm, startLocation 来做到这一点,但遗憾的是,这不起作用。有没有好的方法来做到这一点?我只是搞砸了语法吗?

import axios from 'axios';
import { showAlert } from './alerts';

export const createTour = async myForm => {
  try {
    const startLocation = {
      type: 'Point',
      coordinates: [-80.185942, 25.774772],
      address: '47 Bowman Lane, Kings Park, NY 11754',
      description: 'New York'
    };

    const res = await axios({
      method: 'POST',
      /* headers: {
        'Content-Type': `multipart/form-data; boundary=${myForm._boundary}`
      }, */
      url: 'http://127.0.0.1:8000/api/v1/tours',
      data: myForm
    });

    if (res.data.status === 'success') {
      showAlert('success', 'NEW TOUR CREATED!');
      window.setTimeout(() => {
        location.assign('/');
      }, 1500);
    }
  } catch (err) {
    showAlert('error', err.response.data.message);
  }
};

【问题讨论】:

    标签: javascript node.js mongodb post axios


    【解决方案1】:

    来自 axios 的示例,data 的值应该是 JSON 对象:

    // Send a POST request
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    

    在您的情况下,请尝试以下操作:

        const res = await axios({
          method: 'POST',
          /* headers: {
            'Content-Type': `multipart/form-data; boundary=${myForm._boundary}`
          }, */
          url: 'http://127.0.0.1:8000/api/v1/tours',
          data:{
             form: myForm,
             location: startLocation
          }
        });
    

    那么您应该能够在后端获取表单数据和位置数据。

    参考:Axios API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-22
      • 2020-06-05
      • 2021-05-07
      • 2018-06-16
      • 1970-01-01
      • 2019-02-02
      • 2019-04-26
      相关资源
      最近更新 更多