【问题标题】:axiosjs send FormData from nodeaxiosjs 从节点发送 FormData
【发布时间】:2019-07-18 11:27:00
【问题描述】:

我似乎无法正常工作。 Flightaware 的 api 要求使用表单数据进行发布请求。 Node 不支持表单数据,所以我从https://www.npmjs.com/package/form-data 导入了form-data。然后使用axios,我的代码是这样的。

import { FlightAwareNotification, FlightAwareCredentials } from './models/flightaware';
import { Trip, MilestoneTypes } from './models/trips.model';
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
import axios from 'axios';
import * as FormData from 'form-data';

admin.initializeApp();

const urls = {
    inFlightInfo: FlightAwareCredentials.url + 'InFlightInfo',
    mapFlight: FlightAwareCredentials.url + 'MapFlight',
    setAlert: FlightAwareCredentials.url + 'SetAlert',
}

const AUTH_ENCODED = Buffer.from(`${FlightAwareCredentials.user}:${FlightAwareCredentials.password}`).toString('base64');

export const setFlightAwareAlert = functions.https.onRequest(async (request, response) => {
    const body: {[key: string]: any} = request.body;
    const data = new FormData();
    Object.keys(body).forEach(key => data.append(key, body[key]));
    let alert_id;
    try {
        alert_id = await axios({
            url: urls.setAlert,
            method: 'post',
            data: data,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Basic ${AUTH_ENCODED}`,
            },
            withCredentials: true,
        });
    } catch(err) {
        console.log(err)
    }
    response.json(alert_id && alert_id.data);
});

当我发送请求时,响应是"error": "MISSING: no {channels} specified",这表明它没有正确获取表单数据。

所以我尝试了控制台记录数据,它看起来像这样......

info: FormData {
  _overheadLength: 639,
  _valueLength: 97,
  _valuesToMeasure: [],
  writable: false,
  readable: true,
  dataSize: 0,
  maxDataSize: 2097152,
  pauseStreams: true,
  _released: false,
  _streams: 
   [ '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="alert_id"\r\n\r\n', '0',
     [Function: bound ],
     '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="channels"\r\n\r\n', '{16 e_filed e_departure e_arrival e_diverted e_cancelled}',
     [Function: bound ],
     '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="date_end"\r\n\r\n', '1551056400000',
     [Function: bound ],
     '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="date_start"\r\n\r\n', '1551056400000',
     [Function: bound ],
     '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="ident"\r\n\r\n', 'DAL123456',
     [Function: bound ],
     '----------------------------992898597909585809439236\r\nContent-Disposition: form-data; name="origin"\r\n\r\n', 'KDTW',
     [Function: bound ] ],
  _currentStream: null,
  _boundary: '--------------------------992898597909585809439236' }

【问题讨论】:

    标签: javascript node.js typescript axios


    【解决方案1】:

    以防万一有人遇到这个......

    export const setFlightAwareAlert = functions.https.onRequest(async (request, response) => {
        const body: {[key: string]: any} = request.body;
        const data = new FormData();
        Object.keys(body).forEach(key => data.append(key, body[key]));
        let alert_id;
        try {
            alert_id = await axios.post(urls.setAlert, data, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Basic ${AUTH_ENCODED}`,
                    ...data.getHeaders()
                },
                withCredentials: true
            })
        } catch(err) {
            console.log(err)
        }
        response.json(alert_id && alert_id.data);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多