Sending form data using fetch - node.js

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

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

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

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

How to convert fetch to axios

I have the following piece of code which is working perfect. However, my task is to replace fetch with axios. can you please guide, what would be the correct replacement of code in axios?
const create = async (credentials, software) => {
return await fetch('/api/software/create', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
},
credentials: 'include',
body: JSON.stringify(software)
})
.then((response) => {
return response.json()
}).catch((err) => console.log(err))
}
create({ t: jwt.token }, data)
.then((data) => {
if (data.error) {
this.setState({ error: data.error })
} else {
this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
}
})
The data variable is an object which hold the req.body equivalent...
The above code is written in react and the create() is called within onSubmit eventhandler.
I am sure if I use axios the create() would be eliminated.. but how? Please guide..
It shouldn't be too different than what you currently have but something like this...
const create = async (credentials, software) => {
return await axios({
url: '/api/software/create'
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
},
withCredentials: true,
data: JSON.stringify(software)
})
.then((response) => {
return response.data;
}).catch((err) => console.log(err))
}
create({ t: jwt.token }, data)
.then((data) => {
if (data.error) {
this.setState({ error: data.error })
} else {
this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
}
})
Note that the data you would be looking for should be in a property called data.
For more, check out the API references here.
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()

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