axiosjs从节点发送FormData

时间:2019-02-25 05:03:51

标签: javascript node.js typescript axios

我似乎无法正常工作。 Flightaware的api要求发布请求必须使用表单数据。节点不支持表单数据,因此我从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' }

1 个答案:

答案 0 :(得分:0)

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

c