Axios FormAppend post method and node.js - node.js

I trigger / upload in node.js by calling the submit function inside a class. But in Node.js, req.body is empty. In fact, I append data to FormData in the submit function and send it to node.js. Where am I doing the problem?
Class
submit(){
const data = new FormData()
data.append('file', this.state.selectedFile)
data.append('ID', uniqid())
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}
Node.js
app.post('/upload', (req, res) => {
axios.post('https://....php', req.body, {
}).then(function (response) {
}).catch(function (error) {
console.log('errorserver', error);
});
});

Try to put file after text like this.
submit(){
const data = new FormData()
data.append('ID', uniqid())
data.append('file', this.state.selectedFile)
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}

Related

Not able to POST image files to server

I'm trying to send an image to server using POST request but on server side I'm receiving and empty object.
// Client Side
function uploadFile(thumbnailRef) {
const thumbnail = thumbnailRef.current.files[0];
const formData = new FormData();
formData.append('file', thumbnail)
fetch('http://localhost:8080/upload', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
}).then(res => { console.log(res) })
.catch(err => console.log(err))
}
// server side
app.post('/upload', (req, res) => {
console.log(req.body) // getting empty - {}
res.end()
})
I think it should work if you remove headers. Like this:
function uploadFile(thumbnailRef) {
const thumbnail = thumbnailRef.current.files[0];
const formData = new FormData();
formData.append('file', thumbnail)
fetch('http://localhost:8080/upload', {
method: 'POST',
body: formData,
}).then(res => { console.log(res) })
.catch(err => console.log(err))
}

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

How to download a file from a server, and and post it again in another one (Node.js)

In my node application, I want to get a file from one server, and then upload it into another server. I have the following code:
const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");
const response = await axios({
url: "https://first-server/image.png",
method: "GET",
responseType: "stream",
});
await new Promise((res) => {
response.data.pipe(
createWriteStream("someFile.png").on("finish", () => {
res();
})
);
});
const form = new FormData();
form.append("file", createReadStream("./someFile.png"));
const postHeaders = {
headers: {
Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("https://second-server.com/api", form, postHeaders)
.then((response) => {
console.log(JSON.stringify(response.data));
})
This code works, but I think it's not the right way to do this, since it writes the retrieved file into the local disc before posting it again into the second server. I need to be able to upload the file without writing it into the local disc. Is there any way?
Just replace form.append("file", createReadStream("./someFile.png")); with
form.append("file", response.data);
Both response.data and createReadStream("./someFile.png") are readable stream.
Note: You can directly transfer returned stream data without any need to create temporary file.
const axios = require("axios");
const FormData = require("form-data");
axios({
url: "http://localhost:3000/temp.png",
method: "GET",
responseType: "stream",
}).then(response => {
response.data.on("data", function(data) {
const form = new FormData();
form.append("file", data);
const postHeaders = {
headers: {
// Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("http://localhost:8000/api", form, postHeaders)
.then((response) => {
// console.log(JSON.stringify(response.data));
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});

downloading blank pdf when using express to call looker api

When calling render_task_results(render_task_id) looker API from my NodeJS based API using axios I am getting the binary data but when downloading it it is giving me blank PDF.
PFB my code.
const response = await createPdf(TaskID, lookerToken.access_token);
res.set({ 'Content-Type': 'application/pdf', 'Access-Control-Allow-Origin': '*' });
res.status(200).send(response.body);
return res;
export async function createPdf(TaskID, lookerToken): Promise<any> {
return new Promise((resolve) => {
const url = "someurl/api/3.1/render_tasks/" + TaskID + '/results';
const headers = {
'Authorization': 'token ' + lookerToken
};
axios({
headers,
method: 'get',
url: url,
responseType: 'blob'
}).then((response: any) => {
resolve({
body: response.data
//statusCode: response.status,
});
})
});
}

Sending form data using fetch

I am trying to send form data using fetch. I have the following code:
var toSend = new FormData();
toSend.append('person', 'Peter');
toSend.append('age', '22');
toSend.append('thistext', 'smart');
fetch('http://localhost:3000/sendform', {
method: 'POST',
body: toSend
}).then(res => console.log(res));
And then I am trying to read form data on the backend side with Express using the following code:
app.post("/sendform", function(req, res) {
console.log("processing form data");
console.log(req.body);
res.status(200).send("received");
});
I do have body-parser and etc.
However, req.body is an empty object.
Can anybody help to fix it?
Try this type.
fetch(config.DOMAIN + "user/addPost", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(postData)
})
.then(res => res.json())
.then(post => {
console.log(post)
})
.catch(err => {
console.log(err)
});

Resources