File Uploading using Node js API - javascript

I am really stuck with this issue. I want to upload a file from this API to another API but this code does not seems working when I am sending the form data, it is going as raw content.
form.append('attachment[attachment]', req.files.meeting_attachment);
fetching the data by this way gives source.on is not a function
router.post('/attachments', async (req, res) => {
try {
var form = new FormData();
form.append('meeting_attachment[attachment]', Buffer.from(req.files.meeting_attachment.data), { filename: req.files.meeting_attachment.name });
const options = {
headers: {
'Content-Type': 'multipart/form-data',
'accept': '*/*'
}
};
const url = `https://webhook.site/a307cf34-at22-70b4-3a84-7ef36062d72c`;
const response = await axios.post(url, form, options).then((res) => {
console.log("result", res);
});
res.json({ status: true, data: response.data });
} catch (err) {
console.log("err", err);
res.status(404).json({ status: false, error: 'File type is not supported' });
}
});
I am getting 400 Bad Request with this raw content
Postman request to the actual receiver API looks like this on webhoook and it uploaded the file successfully.

Related

Javascript POST fetch to Express.js server returning 405 (method not allowed)

I'm trying to build an application with Node and Express, and in the script.js file I specify a fetch request to the API POST route I defined, which looks like this:
//Post to the database with a fetch request
fetch("/api/characters", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(character),
})
.then(response => {
if (response.ok) {
return response.json();
}
alert("Error "+response.statusText);
});
The route I defined in server.js looks like this:
//POST a character to the database
app.post("/api/characters", (req, res) => {
let character = req.body;
//Get the db.json file
fs.readFile(path.join(__dirname, "/db/characters.json"), "utf8", (err, data) => {
if (err) {
throw err;
}
if (data) {
let charactersArray = JSON.parse(data);
charactersArray.push(character);
}
fs.writeFileSync(path.join(__dirname, "/db/characters.json"), JSON.stringify(charactersArray, null, 4), (err) => {
if (err) {
throw err;
}
console.log("Successfully wrote character to db");
});
res.send("Successfully wrote character to db");
});
});
I tested the POST route in Insomnia earlier and it looks like it works, so I'm fairly certain the problem lies in the fetch request, but it looks to me like the path and method supplied are correct, so I'm not sure why the POST is saying that it isn't allowed.

Can not download file while sending request from one node.js server to another

I am facing some issue while downloading file using node.js. I have scenario like my angular component is sending the file request. in my first node server I am doing the token validation and then redirecting to another node server where actually the execution happens. I am explaining my code below.
service.ts:
submitAndDownloadFile(formdata : any ){
const token = localStorage.getItem('token')
let headers = new HttpHeaders({
Authorization: 'Basic ' + token
})
const cecID = localStorage.getItem('cec');
const AppUrl = `${environment.nodeJsBaseUrl}:${environment.hostingNodeJsContainerPort}/convert-test-cases/${cecID}`;
return this.httpClient.post(AppUrl, formdata, { responseType: 'blob', observe : 'response', headers : headers});
}
Here I am sending the request to my first node.js server which code has given below.
app.js(first:port-8000):
router.post('/convert-test-cases/:id', middleware.auth, (req, res) => {
try{
let postRequestOptions = {
url: '',
method: 'POST',
json: true,
headers: {},
body: {},
};
postRequestOptions.url = 'http:localhost:9000/convert-test-cases';
postRequestOptions.headers = {
'Content-Type': 'application/json',
};
postRequestOptions.body = req.body;
request(postRequestOptions, async (error, response, pathList) => {
if(error) {
console.log('error', error);
}else{
res.send(pathList);
}
})
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here I am doing the token validation using middleware.auth and sending same request to another node.js file which code is explained below.
app.js:(second-port-9000):
router.post('/convert-test-cases', async (req, res) => {
try{
let response = await ctcCtrl.convertTestCase(req.body, req.files);
if(response.status == 'success'){
res.set('Access-Control-Expose-Headers','*, Content-Disposition');
return res.download(response.fileName,response.fileName);
}else{
return res.send(response);
}
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here only I am doing some execution and downloading the file. If I am connecting angular to node-9000 its working fine but my requirement is first I have to connect to port-8000 to some token validation and after that I have to send same req.body and re.file to app.js which is running in 9000 using request module. As per my code its not working at all.

Can't Post Files using Request or Axios in node js

I have to take data from my form in my front end code and upload the data to another server using API calls, which I am unable to do right now. I have tried numerous ways and tricks mentioned over the internet to solve the problem faced while uploading a file in NodeJs using Request and Axios but none of them are working for just this particular case and I don't know why.
Here is the code in my client-side if we use Axios:
app.post('/job/addjob', upload.any(), (req, res) => {
console.log(req.files[0].path);
var form = new formData();
form.append('Title', req.body.Title);
// form.append('Services', JSON.stringify(req.body.Services));
form.append('Startdate', req.body.Startdate);
form.append('NoOfPositions', req.body.NoOfPositions);
form.append('EndDate', req.body.EndDate);
form.append('Experience', req.body.Experience);
form.append('Rate', req.body.Rate);
form.append('Location', req.body.Location);
form.append('Description', req.body.Description);
// form.append('Questions', JSON.stringify(req.body.Questions));
form.append('Dresscode', fs.createReadStream(req.files[0].path));
axios({
method: 'post',
url: 'http://13.127.239.92:3000/job/addjob',
data: form,
headers: {'Content-Type': 'multipart/form-data', 'Authorization': req.session.verifiedToken}
}).then(function (response) {
console.log(response.data);
res.redirect('/provider');
})
.catch(function (err) {
//handle error
console.log(err);
res.redirect('/profile/getProfile');
});
});
for which the error that I face is
Error Uploading Image.
And here is the code in my client-side if we use Request:
app.post('/job/addjob', upload.any(), (req, res) => {
console.log(req.files);
var options = {
'method': 'POST',
'url': 'http://13.127.239.92:3000/job/addJob',
'headers': {
'Content-Type': 'multipart/form-data',
'Authorization': req.session.verifiedToken
},
formData: {
'Title': req.body.Title,
// form.append('Services', JSON.stringify(req.body.Services));
'Startdate': req.body.Startdate,
'NoOfPositions': req.body.NoOfPositions,
'EndDate': req.body.EndDate,
'Experience': req.body.Experience,
'Rate': req.body.Rate,
'Location': req.body.Location,
'Description': req.body.Description,
// form.append('Questions', JSON.stringify(req.body.Questions));
'Dresscode1': fs.createReadStream(req.files[0].path),
}
};
request(options, function (error, response) {
if (error) { console.log(error) }
else {
console.log(response.data);
res.redirect('/provider');
}
});
});
for which the error that I face is:
{ Error: socket hang up
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }
This is the fraction of code from the server-side which might come in handy understanding my problem:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'dresscodes/')
},
filename: function (req, file, cb) {
let uuid=v4();
cb(null, uuid +"."+mime.getExtension(file.mimetype))
pp= uuid +"."+mime.getExtension(file.mimetype);
}
});
let upload = multer({ storage: storage }).any();
upload(req,res,function(err) {
if(err) {
console.log(err);
return res.end("Error uploading image.");
} else{
var fullUrl = req.protocol + '://' + req.get('host') ;
Now to the worst part, I can only make changes to my client-side code and not to the server-side code

Svelte/Sapper: Body empty on POST

I'm trying to create a login form using sapper, but am encountering the following problem when trying to test a basic POST fetch.
In routes/login/login.svelte, I have the following code which is called on a button click:
<script>
let data = {"email":"test"};
const handleLogin = async () => {
const response = await fetch("/login/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: data
});
};
</script>
Which should send what is in data to routes/login/login.js which has the following code:
export async function post(req, res, next) {
res.setHeader('Content-Type', 'application/json');
var data = req.body;
return res.end(JSON.stringify(data));
}
My problem is that this only returns {} rather than the data sent in the svelte page. Any ideas as to why this is happening and where I'm going wrong? Thanks.
When sending the data, you should also stringify it there
body: JSON.stringify(data)
as an extra make sure you have body-parser installed and added as middleware in the server, this package will help you handle requests that have send json data in their body.
polka() // You can also use Express
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
bodyparser(),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
Building on the previous answer, I'm writing here the full working solution. Your problems may be due to:
Not using the json parse middleware
Not treating fetch as a promise
Here's how I'd fix it:
npm i body-parser
Add the json middleware in your server.js
const { json } = require('body-parser');
polka()
.use(
compression({ threshold: 0 }),
json(),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
Treat the fetch response as a Promise. This is how your Svelte component should look like (notice the chained then):
<script>
let data = {"email":"test"};
const handleLogin = async () => {
await fetch(`your-endpoint`, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(res => console.log(res)); // {email: "test"}
};
</script>

difference between api call and on postman

I was using Azure Speech rest api. And i tried it on post man with a .wav file and it successfully return the result. However, when i call api from my node.js code. It always return Unsupported Audio Format even though i give the same audio file. Can anyone tell me what's the difference of them? Or what did Postman do to make it work?
Below is how i call speech api by node.js.
'use strict';
const request = require('request');
const subscriptionKey = 'MYSUBSCRIPTIONKEY';
const uriBase = 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US';
const options = {
uri: uriBase,
body: 'speech.wav',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key' : subscriptionKey,
'Transfer-Encoding': 'chunked',
'Expect': '100-continue',
'Content-type':'audio/wav; codec=audio/pcm; samplerate=16000'
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonResponse = JSON.stringify(JSON.parse(body), null, ' ');
console.log('JSON Response\n');
console.log(jsonResponse);
});
You can try this
fs.readFile('/path/to/my/audiofile.wav', function (err, data) {
if (err) throw err;
var options = {
host: 'https://westus.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US',
method: 'POST',
headers: { 'Content-Type': 'audio/wav' }
};
var req = http.request(options, function(res) {
// Handle a successful response here...
});
req.on('error', function(e) {
// Handle an error response here...
});
// Write the audio data in the request body.
req.write(data);
req.end();
});

Categories

Resources