Not able to POST image files to server - node.js

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))
}

Related

Axios FormAppend post method and 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 => {
});
}

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)
});

react native cannot get appended data in server side

I want to upload image to the database. However, when I use fetch method with 'Content-Type': 'multipart/form-data' but I cannot get the appended data in the server side. It shows that I have no data in the body.
Below is fetching part of the coding
editProfile = () => {
let bodyData = new FormData();
let photo={
uri:this.state.uri,
type:this.state.type,
fileName:this.state.fileName,
}
bodyData.append('transactionCode', 'UPDATEPROFILE');
// bodyData.append('photo', photo);
console.log(bodyData);
fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: bodyData,
}).then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
})
.catch((error) => {
alert(error);
});
}
This is the example of how i check the data at the server side
const custfunction = function (req, res) {
console.log(req.body);
}
When i console.log(req), it shows body:{} is empty
Alright, I just find out the problem. I need to use Multer to handle multipart/form-data in the backend. Thanks a lot.
https://www.npmjs.com/package/multer

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)
});

How to show the success response from node server on react-redux framework

I am making a demo react-redux app for the basic understanding of redux and its server is made on nodeJS. I have made a simple form which gets submitted and the server response is res.send('FORM SAVED'). In front-end, I make the post request but is not able to see the response that returns, be it the success response.
My server controller that responds when form details are saved.
export const postData = (req, res) => {
let p = new PostData();
p.name = req.body.name;
p.emp_id = req.body.emp_id;
p.age = req.body.age;
p.dept = req.body.dept;
p.phone = req.body.phone;
p.gender = req.body.gender;
p.save(((err) => {
if (err){res.send(`Error in uploading: ${err}`);}
else {res.send('Form saved');}
}));
}
This is my action:-
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then((post) => {
console.log('post:', post);
dispatch({
type: NEW_POST,
payload: post
})
})
}
This is how I call this in component after clicking submit:-
onSubmit = (e) => {
e.preventDefault();
let postData = {
name: this.state.name,
emp_id: this.state.emp_id,
dept: this.state.dept,
gender: this.state.gender,
age: this.state.age,
phone: this.state.phone
}
this.props.createPost(postData);
}
I want to get the response string ('Form saved') but I don't know how to read that. Can anyone help? Thanks in advance
fetch returns a raw response object. To get an expected data you should call a .json() method on raw response object which is returned by fetch, like below:
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json()) // add this line
.then((post) => {
console.log('post:', post); // you should get an object with `Form saved` or something similar to it
dispatch({
type: NEW_POST,
payload: postData // replace it to the input parameter
})
})
}
Using async/await it becomes more readable:
export const createPost = (postData) => async (dispatch) => {
// send postData to server
const rawResponse = await fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
// we are done with server but we need one more step
// turn a raw response to readable JS object
const message = await rawResponse.json()
// message from server response
console.log('Message ', message);
// store same object as we sent to server in redux store
dispatch({ type: NEW_POST, payload: postData });
}
Hope it helps

Resources