I am required to send a CSV file stored in my computer to another external API. The CSV file contains some data and it is stored in my computer I need to create an API in NodeJS that sends this CSV file to another server using POST method and with the right headers like:
-H 'accept: application/json' -H 'Authorization: Bearer token -H 'Content-Type: multipart/form-data' -F 'csvFile=@New1.csv;type=text/csv'
How can it be achieved? Please help Thanks
const dbConnect = require('../../config/dbConnect')
const mssql = require('mssql/msnodesqlv8')
const DBConstants = require('../utils/constants')
const dbConfig = require('../../config/database')
const converter = require('json-2-csv')
const fs = require('fs')
const axios = require('axios')
const https = require('https')
const formData = require('form-data')
module.exports.getData = async(req, res) => {
const httpsAgent = new https.Agent({rejectUnauthorized: false})
const form_data = new formData()
let pool, result, request_config
var token
// get data from sp
try {
pool = await dbConnect
result = await pool.request()
.input(**************)
.input(************)
.execute(**********)
} catch (err) {
console.log('Error fetching records from store procedure', err)
}
// convert fetched data into csv
converter.json2csv(result.recordsets[0], (err, csv) => {
if(err) {
throw err
} else {
fs.writeFileSync('DATA.csv', csv)
}
})
form_data.append('csvFile', fs.createReadStream("DATA.csv"))
// login to external API
axios.post('/api/v1/user/login', {
email: 'login_email',
password: 'login_pass'
}, { httpsAgent } )
.then(response => {
token = response.data.token
// now create request_config
request_config = {
headers: {
"accept": "application/json, text/csv",
"Authorization": "Bearer " + token,
"Content-Type": "multipart/form-data",
...form_data.getHeaders()
},
httpsAgent,
maxContentLength: Infinity,
maxBodyLength: Infinity,
}
})
.catch(err => {
console.log(err)
})
// Making the Upload Call
axios.post('/api/v1/amc/upload/', form_data, request_config)
.then(response => {
res.json(response)
})
.catch(err => {
console.log('error in upload', err)
})
res.json(result.recordsets[0])
}