Passing data to a webservice using axios from a react application - reactjs

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

Related

Can't complete a PUT request from a different Modal using fetch with React

I am trying to create a CRUD app using springboot and React.
I have a problem with the PUT request to update a record from MySQL database.
With postman, when I send A PUT request like this:
{
"id": 456,
"name": "CHANGED_NAME",
"surname": "SURNAME",
"gender": "M",
"birthdate": "1995-12-07",
"work_address": "address1",
"home_address": "address2"
},
to http://localhost:8080/users/456
it works fine.
I have the info in a ListUsers.jsx file and I am trying to make the update from another jsx, e.x. UpdateUser.jsx sending as default values the current values when calling the UpdateUser Component.
Inside the UpdateUser.jsx I have a Form and onSubmit I call the handleSumbit method to make the PUT request, but nothing happens.
handleSubmit(event){
event.preventDefault();
fetch('http://localhost:8080/users/'+event.target.userId.value,{
method:'PUT',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
id: event.target.userId.value,
name: event.target.name.value,
surname: event.target.surname.value,
gender: event.target.gender.value,
birthdate: event.target.birthdate.value,
work_address: event.target.work_address.value,
home_address: event.target.home_address.value,
})
})
.then(res=> res.json())
.then((result)=>
{
//alert(result);
this.setState({user_added:true});
},
(error)=>{
//alert('Failed')
this.setState({user_added:true});
}
);
event.target.reset();
}

How to receive a response to React from FastAPI when Postman receives a response?

I have a FastAPI server running at localhost:8000 and a react dev server running at localhost:3000. I have an endpoint set up as follows:
#router.post(
name="Create User",
tags=[Tags.Authentication],
path='/create_user',
status_code=200,
response_model=SuccessfulUserAuthenticate
)
def create_user(
user: UserInCreate = Body(
title="User",
description="User that will be created",
default=Required,
embed=True
)
):
pwd_context = CryptContext(schemes=['bcrypt'], deprecated="auto")
new_user_object = User(
user.first_name,
user.last_name,
user.email,
pwd_context.hash(user.password),
user.dob)
with Session() as s:
user_already_exists = True if s.query(User).where(User.email == user.email).first() else False
if user_already_exists:
raise EmailAlreadyExistsException()
else:
new_user_object.datetime_joined = datetime.utcnow()
s.add(new_user_object)
s.commit()
return_user = SuccessfulUserAuthenticate(
user.email,
create_access_token(
data={
'user': user.email
}
)
)
return return_user
Long story short, this function simply checks whether the email exists on the database. If it does, it raises an error which is handled by an exception handler which looks as such:
#app.exception_handler(EmailAlreadyExistsException)
def email_exists_exception_handler(request: Request, exc: EmailAlreadyExistsException):
print('here')
return JSONResponse(
status_code=exc.status_code,
content=jsonable_encoder({'detail': exc.description})
)
If the email does not exist, it creates an account in the database. As you can see, I have a little debug statement which shows up in my terminal. The react frontend fetch function looks as such:
const createUserSignUpSubmit = async () => {
const response = await fetch('http://localhost:8000/authentication/create_user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"user": {
"email": "user#example.com",
"password": "string",
"first_name": "string",
"last_name": "string",
"dob": "2019-08-24"
}
})
})
console.log(response.status)
console.log(response.body)
setFirstName('')
setLastName('')
setEmail('')
setPassword('')
setDate(new Date())
}
When I submit this fetch request, I know that it reaches the endpoint because I can see the sql statements print out to the terminal and they look as follows:
2022-09-22 18:22:12,178 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2022-09-22 18:22:12,184 INFO sqlalchemy.engine.Engine SELECT user.id AS user_id, user.first_name AS user_first_name, user.last_name AS user_last_name, user.email AS user_email, user.password AS user_password, user.datetime_joined AS user_datetime_joined, user.date_of_birth AS user_date_of_birth
FROM user
WHERE user.email = %s
LIMIT %s
2022-09-22 18:22:12,184 INFO sqlalchemy.engine.Engine [generated in 0.00023s] ('user4#example.com', 1)
2022-09-22 18:22:12,191 INFO sqlalchemy.engine.Engine ROLLBACK
here
The "here" is printed from the exception handler. So everything flows as you would expect but it just wont return a response to my frontend. It does properly return a response to postman however. After much searching, I can't seem to figure out the issue. I've concluded that it isn't a CORS issue because I have the appropriate middleware set up as well as follows:
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
It seems as if the code is flowing just as I want it to, all the way until the final step where it actually has to send a response back to React. Any help would be greatly appreciated!
So after some debugging, I've realized that my mistake was that I forgot to call e.preventDefault() in the method that performs the fetch request. As a result of that, the page would reload and my API wouldn't have anywhere to send the response back to. It's working as intended now.

POST method JSON not updating JSON server local file

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?

Get the image from the server

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

How to post data when you have javascript object using multipart/form-data content-type

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.

Resources