【问题标题】:POST request with form data fails after switching from request-promise to node-fetch从 request-promise 切换到 node-fetch 后,带有表单数据的 POST 请求失败
【发布时间】:2020-11-21 20:23:11
【问题描述】:

我已将request-promise 替换为node-fetch。除了一个请求之外,一切都运行良好,它将表单数据发送到一个端点,不幸的是,我无法在此处提供。这是与request-promise 一起使用的代码:

const options = {
    method: 'POST',
    uri: keys.endpointUrl,
    formData: {
        operations: JSON.stringify(operations),
        map: JSON.stringify(map)
    },
    json: true
};

const response = await request(options);

移动到node-fetch后,是这样的:

const FormData = require('formdata-node');

const form = new FormData();

form.set('operations', JSON.stringify(operations));
form.set('map', JSON.stringify(map));

const opts = {
    method: 'POST',
    body: form
};

const res = await fetch(keys.endpointUrl, opts);

console.log(res);

const response = res.json();

res 记录为:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: true,
      _transformState: [Object],
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    status: 500,
    statusText: 'Internal Server Error',
    headers: Headers { [Symbol(map)]: [Object: null prototype] }
  }
}

我尝试添加不同的标题,但不幸的是,它一直失败。我错过了什么?

NodeJS:v12.16.1 节点获取:2.6.0

【问题讨论】:

    标签: node.js request form-data node-fetch


    【解决方案1】:

    除非您上传文件,否则您不需要 FormData

    const fetch = require('node-fetch');
    
    var form = {
      "operations": JSON.stringify(operations),
      "map": JSON.stringify(map)
    }
    
    const opts = {
        method: 'POST',
        body: form
    };
    
    const res = await fetch(keys.endpointUrl, opts);
    

    【讨论】:

      【解决方案2】:

      我的猜测是您需要将content-type 标头设置为x-www-form-urlencoded,这可能是您的端点所期望的。注意documentation

      仅当 URLSearchParams 的实例这样给出时,Content-Type 标头才会自动设置为 x-www-form-urlencoded:

      【讨论】:

        猜你喜欢
        • 2016-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-08
        • 2018-04-30
        • 2018-01-23
        • 2018-07-17
        • 2016-10-29
        相关资源
        最近更新 更多