I am creating a rest API server in Express.js. The goal of this of my particular issue is creating a post route that takes multipart/form-data request and sends file/text/field to an external API. At the moment I am running into an issue even trying to test it with postman.
I can send a response with the parsed data from multer, but when I try to create a new form-data I cannot access the request body, TypeError: Cannot read property 'name' of null
What am I doing wrong? Is there a better way? Open to suggestions.
My server code is as follows:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const request = require("request");
const multer = require("multer");
const upload = multer({ dest: 'uploads/'});
const FormData = require("form-data");
const fs = require("fs");
const app = express();
const port = 3000;
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
///.....
app.post('/jobs/:id', upload.single('resume'), (req, res) => {
let url = '...';
var header = req.headers['content-type']
var tmp_path = req.file.path;
var tar_path = 'uploads/' + req.file.originalname;
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(tar_path);
src.pipe(dest);
var data = new FormData();
data.append('name', req.body.name)
data.append('phone', req.body.phone)
data.append('email', req.body.email)
data.append('resume', fs.createReadStream(tar_path))
const options = {
url: url,
method: 'POST',
headers:{
'Content-Type': header
},
formData: data
}
request(options, (err, rez, body) => {
if (err){
console.log("There was an error: " + err)
}
}).pipe(res)
res.send(res)
})
app.listen(port, () => console.log(`Server is listening on port ${port}`));
EDIT
This is the request I am trying to make:
curl -F name="test" -F phone="0000000000" -F email="[email protected]" -F resume=@"Desktop/test.txt" http://cfr.thewb.co/jobs/408189/
curl?