I have setup a POST method on the submit handler of my react app. But every time I submit the form, the JSON server just registers the id, and not the content, as shown below:
Output Image
Json Server local file
As you can see, the app can display the user input's newly submitted form, but it can't be registered in the json server, as it only shows the id. Here is the snippet for the Submit handler function of the form:
const formSubmitHandler = (event) => {
event.preventDefault();
if (!enteredFNameValid || !enteredLNameValid) {
alert("First Name and Last Name accepts letters only.");
return;
}
const newInputData = {
fName: enteredFName,
lName: enteredLName,
email: enteredEmail,
eid: enteredEid,
birthday: enteredBirthday,
};
const allInputData = [...inputData, newInputData];
setInputData(allInputData);
// console.log(allInputData);
fetch("http://localhost:3001/inputData/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify[newInputData],
}).then((res) => {
console.log("new post added");
alert("Success!");
});
};
I've tried to change the body to an object as {newInputData}, but it just creates a new set of array, and registers that as the new entry for the JSON's generated id.
Hope to have insights from ya'll. Thank you.
Maybe it's an issue with square brackets on the JSON.stringify?
Did you take a look at this post?
Related
I uploaded an image file using axios post method and it was successfully uploaded to the server...
On return to the POST method, it returned the Image URL as:
{imageUrl: "/root/TTAppJava/images/players/Screenshot from 2020-11-24 16-38-57.png"}
Now, I want to display the image onto my screen.
How can I get that image?
I am using React.js to implement this.
The URL I used to post the image is:
http://139.59.16.180:8269/player/details/${id}
I am doing this to upload my data:
var formData = new FormData()
formData.append("file", image);
const theWrapper = {
"data": {
"name": name,
"age": age,
"email": email,
"gender": gender
}
}
formData.append("theWrapper", JSON.stringify(theWrapper))
Axios.post("http://139.59.16.180:8269/player/add",
formData,
{ headers: { Authorization: "Bearer " + localStorage.getItem("token") } }
).then(res => {
console.log(res)
alert("Player added successfully.")
history.push("/players")
})
.catch(err => alert(err.messge))
And the response I am getting is:
{id: 14, name: "shreyas", email: "asdfjka#gmail.com", gender: "Male", imageUrl: "/root/TTAppJava/images/players/Screenshot from 2020-11-24 16-38-57.png", …}
I will give you an example how its done in Node app, since the underlying concept will be the same as I am not a Java developer.
First please note your image_url/download_url should be saved as follows,
https://yourdomain/folder/image_name
example: http://localhost:3000/uploads_folder/my_image_name.jpg
and then you need a route in Java Spring which figures out what image to send to the front-end as Stream like below,
router.get("/:folder/:image_name", async (req, res) => {
const { folder, image_name } = req.params;
// find an image based on the downloadUrl in the folder where files are saved.
// Please note, after uploading file successfully generate a download url
// appropriately so that this route can help figure out which image you
// are looking for.
const file = path.join(`path/to/${folder}`, `${image_name}`);
// Figure out a way how stream works in your context.
// Providing MIME type is important!
const type = mime[path.extname(file).slice(1)] || "image/jpg";
const s = fs.createReadStream(file);
s.on("open", () => {
res.set("Content-Type", type);
s.pipe(res);
});
s.on("error", (err) => {
// Handle Error
});
});
So I have never post a data using FormData and multipart/form-data as Content-Type in my React project. But now I'm kinda forced by backend to send it this way since we have some images in payload.
The problem is that the whole data is a JS object and can be parsed to JSON, and nothing more. So how can I convert my JS object into a valid FormData that backend would accept it? Everything works without a problem in Postman, but in the app I always get the same error.
Here is some more detail:
The working Postman sample:
What I expect to be working (but obviously doesn't):
const createProd = () =>
HttpRequest.post('/api/prod', {
body: {
Product: {
title: 'Test Prod',
shop: null,
description: "My new ad's description",
category: { id: '5d8c6aa6fadeaf26b0194667' },
condition: 'USED'
}
});
HttpRequest is a helper function which uses ES6 fetch for requests.
I always get the same error: "Required request part 'Product' is not present" with/without JSON.stringify.
I even tried to create a sample FormData to at least change the error:
cont payload = new FormData();
payload.append('Product', {foo: 'bar'});
But still same error. I also copied the code which is generated by Postman. But still no chance.
I would be thankful if you share your suggestions or workarounds.
Thanks in advance.
const formData = new FormData();
const product = { //your product object };
formData.append('product', JSON.stringify(product));
const config = {
headers: {
'Content-Type': 'multipart/form-data; charset=utf-8; boundary="another cool boundary";'
}
};
axios.post(`/api/ads`, formData, config).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
});
Maybe you should set header.
Try this one. In my case I used Axios. It worked for me in my project.
Below is the Request Payload, I need to add few other fields present on my Form.
comment: ""
ownership: "47"
parts: []
placeIdToRepair: "ABC"
requestCategory: "STD"
requestType: "REP"
returnReason: "3RO"
returnType: "STD" ```
Using fetch API after extracting your form fields
const handleSubmit = event => { /* function passed to onSubmit event on your form */
event.preventDefault(); /* preventing browser from reloading */
fetch(/* URL */, {
method: ”POST",
headers: {
”content-type": "application/json"
},
body: JSON.stringify({ /* and finally */
/* form key: form value */
})
}}
I hope I understood you question
I have an intellij project running a webservice in localhost:8022. when I run this project
and use this url(http://localhost:8022/api/vi/solutionj/solutionj-requests) to post the data using postman
it works very well. My data gets written to the database. This simply shows that I can reach this url.
{
"branchId": 1,
"customerEmail": "john#yahoo.com",
"firstName": "Johnny",
"lastName": "Jacob"
}
However, I need to pass this data from a react application and on the click of a button
I call the function below. I am using Axios.
I set a breakpoint in my intellij project and I am not able to hit the endpoint. I decided to
think whether am using axios the wrong way.
handleDatabaseStorage = (branchId, customerEmail, firstName, lastName) => {
//webapi url
const SOLUTIONJ_BASE_URL = `http://localhost:8022/api/vi/solutionj/solutionj-requests`;
try {
AXIOS_AUTHED.post(SOLUTIONJ_BASE_URL, {
branchId: branchId,
customerEmail: customerEmail,
firstName: firstName,
lastName: lastName
});
} catch (error) {
console.error(error);
}
};
What am I doing wrong in the code above? I am not getting any error back and the data is
not written to my database. I need to be able to know if there is an exception. My webservice is expecting
all the fields above.
You can use .then and .catch to get the success and error response respectively.
AXIOS_AUTHED.post(SOLUTIONJ_BASE_URL, {
branchId: branchId,
customerEmail: customerEmail,
firstName: firstName,
lastName: lastName
},{
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
use like this
const SOLUTIONJ_BASE_URL = `http://localhost:8022/api/vi/solutionj/solutionj-requests`;
let data = {
branchId: branchId,
customerEmail: customerEmail,
firstName: firstName,
lastName: lastName
}
let reqObj = {
method:'POST',
data:data, //above data variable
url:SOLUTIONJ_BASE_URL
}
axios(reqObj)
.then((res)=>{console.log(res)})
.catch((err)=>{console.log(err)})
I'm using Apollo with the Scaphold.io service and for writing blobs to that service I need to be able to add additional options to the request body.
The full Scaphold example can be found here: https://scaphold.io/docs/#uploading-files
But it does something like this:
form.append("variables", JSON.stringify({
"input": {
"name": "Mark Zuck Profile Picture",
"userId": "VXNlcjoxMA==",
"blobFieldName": "myBlobField"
}
}));
// The file's key matches the value of the field `blobFieldName` in the variables
form.append("myBlobField", fs.createReadStream('./mark-zuckerberg.jpg'));
fetch("https://us-west-2.api.scaphold.io/graphql/scaphold-graphql", {
method: 'POST',
body: form
}).then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
});
Where it adds a blobField to the request body.
Based on this, I need to pass into the variables a blobFieldName property, and then add to the request body the value passed to that property with the blob. However, using Apollo I can't add to the request body. I tried the following, but it's absent from the request body when I check in the network inspector:
export const withCreateCoverPhoto = graphql(CreateCoverPhoto, {
props: ({mutate}) => ({
createCoverPhoto: (name, file) => mutate({
variables: {
input: {
blobFieldName: name,
},
},
[name]: file
}),
}),
});
Please advise.
Thanks for the question. Currently the best way to upload files is by [appending it to FormData and sending it up to the server using fetch] (https://medium.com/#danielbuechele/file-uploads-with-graphql-and-apollo-5502bbf3941e). Basically, you won't be able to have caching here for the file itself, but this is the best way to handle uploading files on Scaphold using a multipart request.