Error trying to POST request from react to nodeJS - javascript

I'm trying to post a new object to my mongodb collection which is handled on my backend server, but the values from my request body are not passed to it.
I can guarantee that the object is created. The problem is that all the object values are empty.
I also guarantee that the nodejs code works correctly. The first thing I did was create a web application just using nodeJS and from that page I can create a new object normally.
But now I'm creating a frontend page using react and I'm not sure why my frontend page's post request doesn't work as intended
react code:
const handleSubmit = async (event) => {
event.preventDefault();
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name:nome,
cnpj:cnpj,
email:email,
number:telefone,
seguradora:[seguradora],
index:765756
})
};
try{
const response = await fetch('http://localhost:3001/corretoras',requestOptions)
const data = await response.json()
console.log(data)
console.log(requestOptions.body)
}
catch(error){
console.log('error trying to post',error)
}
};
nodeJS code:
router.post('/',async(req,res)=>{
const lastIndex = await Corretora.find().sort({index:-1}).limit(1).index
const corretora = new Corretora({
name:req.body.name,
cnpj: req.body.cnpj,
email:req.body.email,
number:req.body.number,
seguradora:req.body.seguradora,
index: lastIndex
})
try{
const novaCorretora = await corretora.save()
res.redirect('corretoras/'+novaCorretora.id)
}
catch{
renderNewPage(res,corretora,true)
}
})
console log from react code:

Found my issue. I didn't type app.use(express.json()) in my server.js

Related

How do I acquire the data in a json response from a POST request in Next/React?

I am using Next.js api route to handle a POST request then send a response back to the frontend. I have used Rapid API client extension to confirm there is a response being sent to the frontend. I just dont know how to handle it in the frontend.
Here is the code on the api route:
import clientPromise from "../../../config/mongodb";
export default async function userDetailsHandler(req, res) {
const body = req.body;
if (req.method == "POST") {
const client = await clientPromise;
const db = client.db("mood-board");
let emailQuery = await db
.collection("users")
.find({ email: body.email })
.limit(1)
.toArray();
let parsedData = JSON.parse(JSON.stringify(emailQuery));
res.status(200).json(parsedData)
console.log(parsedData)
} else if(req.method = "GET") {
}
}
In the following example, you use the fetch api to post the data which returns a promise. You can use then() which takes a callback function that you can use to operate on the data once that promise is returned.
Example:
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example' })
};
fetch('https://reqres.in/api/posts', requestOptions)
.then(response => response.json())
.then(data => setPostId(data.id));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);

Issue with sending FormData from backend

I have a component which processes and uploads images. Currently I process the image on my backend and then send it to my frontend and then upload it from there. I would like to do everything on my backend. The only issue is that the upload endpoint requires FormData() object. I found an npm package form-data which I'm using on my backend now, but I'm still getting error.
This is how it currently works:
// frontend logic:
const data = await uploadImage(img);
const file = new File([Buffer.from(data)], `img-${i}.webp`, {
type: "image/webp",
});
const formData = new FormData();
formData.append("path", "images");
formData.append("files", file, file.name);
await axios
.post("http://localhost:1338/api/upload", formData, {
headers: { authorization: `Bearer ${jwtToken}` },
})
.then(({ data }) => {
console.log(data);
})
.catch(console.log);
//
//
// backend logic:
const data = await processImage(img.url);
return data;
This is what im trying to do:
// frontend logic:
const data = await uploadImage(img);
//
//
// backend logic:
const data = await processImage(img.url);
const formData = new FormData();
formData.append("path", "images");
formData.append("files", data, "file.name");
await axios
.post("http://localhost:1338/api/upload", formData, {
headers: { authorization: `Bearer ${process.env.JWT_TOKEN}` },
})
.then(({ data }) => {
console.log(data);
})
.catch(console.log); // I get error: 413 Payload Too Large
I'm trying to do it with the same image which works with the first method. Perhaps I need to create a new File(), but I couldn't find any npm packages which worked for that. What should I do to get this working?

Expo Formdata does not working for to send a image to api rest

Hi Everybody i making a web frontend using expo SDK 39.0.2 but i have a big problend and really i not found a fix, im trying to send image like formdata to my backend but in mi backend this is null; this is not a problem of my api rest, i send a similar tequest from postman and all is’t working… but not working from formdata and I think : “this is problem with my way of to send formdata”
this is my code:
//Component code
const imagepreview = async()=>{
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: false,
aspect: [4, 3],
quality: 0.6,
});
console.log(result)
if(result.cancelled == false){
setImage(result.uri)
let uriParts = result.uri.split('.');
let fileType = uriParts[uriParts.length - 1];
settype(fileType)
}
}
const sendData = async()=>{
// Upload the image using the fetch and FormData APIs
let formData = await new FormData();
// Assume "photo" is the name of the form field the server expects
await formData.append('photo', {
name: `photo.${type}`,
type: `image/${type}`,
uri: image,
});
const send = await user.changeprofilepicture(formData)
my http request code:
async changeprofilepicture(formdata){
console.log(formdata)
const token = JSON.parse(localStorage.getItem('user-token'))
let url = baseurl+'changeprofilepicture'
let options = {
headers: {
'content-type': 'multipart/form-data'
}
}
await axios.post(url, formdata, options)
await axios.post(url, {
photo: formdata
}, {headers :
{'Content-Type':undefined}})
}
i have two http request for im triying two ways for solved my broblem but does not works, only works at postman
really, thanks for te answers
Finally I solved..
I Change expo image picker for expo document picker like this:
const imagepreview = async()=>{
const trye = await DocumentPicker.getDocumentAsync({type: 'image/*'})
setFile(trye.file)
setImage(trye.uri)
console.log (trye)
}
const sendData = async()=>{
formData.append('photo', file);
console.log(file)
return await fetch('http://127.0.0.1:3333/api/changeprofilepicture', {
method: 'POST',
body: formData,
});
}

can't get success response data/status from node/express to my client app(react): "referenceerror response is not defined"

i've made a basic node/express server, and have a route that handles submission of form data(i've made using react), the post request is handled using async/await with fetch api.. i'm not sure if the issue is with my server-side route or my implementation of the post request with async/await fetch. however the server does receive the form data it just doesn't return a response.
my code:
node/express route
router.post('/add', function (req, res) {
console.log(req.body);
res.json({success : "Updated Successfully", status : 200});
});
note: the console.log(prints the expected data, but the response isn't being picked up by client correcly)
post request implementation:
const postRequestHelper = async (routePath, objectPayload) => {
console.log("posting payload object: ");
console.log(objectPayload);
const rawResponse = await fetch(routePath, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objectPayload)
});
const response = await rawResponse.json();
return response;
};
export default postRequestHelper;
form submission code where post request is called:
async handleSubmit(event) {
if(typeof this.state.validationMessages === "undefined"){
// create payload data object
let objectPayload = Object.assign({}, this.state);
for(let key in objectPayload){
if(!isInObject(key, formKeyConstants)) // delete any prop keys that aren't in formPropertyKeys js file
delete objectPayload[key]
}
// send post request
console.log(objectPayload);
const response = await postRequestHelper("http://localhost:8080/user/add", objectPayload);
// log response data
console.log("response");
console.log(response);
}
event.preventDefault();
}
What about trying in your server
return res.send(JSON.stringify({success : "Updated Successfully", status : 200}));
issue was with async await fetch api it seems, issue with await was breaking the response from the server.
If routing takes place in app , then use :
app.use(express.json)
If routing takes place in router folder , then use :
router.use(express.json)
It'll by default uncover the req.body into json format.(For which installing and initializing express is a must)

Add parameters to post request using js on client side

I'm developing a "TODO" app using node.js and mongodb.
I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.
Client code:
<script>
function addData(item, url) {
var text = document.getElementById("myTask").value;
return fetch('/todos',{
method: 'post',
body: text
}).then(response => response.json())
.then(data => console.log(data));
}
</script>
Server code:
app.post('/todos',(req,res) =>{
console.log("\n\n req.body is: \n\n",req.body);
var todo = new Todo({
text: req.body.text});
todo.save().then((doc) =>{
res.send(doc);
console.log(JSON.stringify(doc,undefined,2));
},(err) =>{
res.status(400).send(err); //400 = unable to connect
console.log("Unable to save todo.\n\n\n" , err);
});
});
And the problem is that the client doesn't send the body to the server,
and the body is null on the server side:
See the logs here
(as you can see: req.body = {})
In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)
Thank in advance,
Sagiv
I think that you are missing something. Try to use name of param
body: JSON.stringify({data: text})
OR
read here Fetch: POST json data
I used this code:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
and now I succeeded to pass data to the request.
Thanks everybody

Categories

Resources