Backend services are working correctly. I'm trying to set the header parameter. But I am making a mistake somewhere. I can't get a response.
Error appearing in console: Request failed with status code 417
How can I solve it?
PolicyService.js
const getAsosPaymentInfo = (getPolicyAccountInfoRequestDto) => {
return new Observable((observer) => { // <PaymentInfoResponseDto>
axiosInstance
.post(SERVICE_PATH + '/getAsosPaymentInfo', getPolicyAccountInfoRequestDto, {
headers: { 'sales-channel': 200008, 'agency-code': 10038, 'content-type': 'application/json' }
})
.then((response) => {
observer.next(response.data);
observer.complete();
})
.catch((err) => {
console.log(err);
});
});
};
policy-payment-info.js
const req = {
policyNumber: '1277976920',
renewalNumber: '01',
policyTypeExtCode: '800',
productTypeExtCode: '2000062'
};
useEffect(() => {
if (props.location.state.policy.isActive === true) {
PolicyService.getAsosPaymentInfo(req).subscribe(
(response) => {
console.log(response);
}
);
}
}, []);
I am working on a reactjs project and I am trying to capture the HTML for creating images including the canvas of signature. It's working on firefox and chrome but not safari. Image is generated with the empty canvas.
React Signature Canvas
Html To Image
this.setState({ formInput: document.getElementById("form-pdf") })
generateImage(data) {
const input = this.state.formInput;
let apiService = new ApiServices();
if (input) {
await htmlToImage.toBlob(input)
.then((blob) => {
console.log(blob,'blob')
let file = new File([blob], "image.png", { type: "image/png" })
if (data) {
let body = new FormData();
apiService.http.post(this.getAPINames().Upload, body, {
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
timeout: 100000,
}).then(response => {
console.log("Success")
}).catch(failure => {
hideLoader();
if (isDev) {
console.log("on upload image error:", failure)
}
});
}
})
.catch((error) => {
if (isDev) {
console.log(error)
}
})
}
}
I've resolved this problem just with a double execution of the html-to-image function, so in your case it could be like this:
generateImage(data) {
const input = this.state.formInput;
let apiService = new ApiServices();
if (input) {
await htmlToImage.toBlob(input)
.then(function(){
await htmlToImage.toBlob(input)
.then((blob) => {
console.log(blob,'blob')
let file = new File([blob], "image.png", { type: "image/png" })
if (data) {
let body = new FormData();
apiService.http.post(this.getAPINames().Upload, body, {
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
timeout: 100000,
}).then(response => {
console.log("Success")
}).catch(failure => {
hideLoader();
if (isDev) {
console.log("on upload image error:", failure)
}
});
}
})
.catch((error) => {
if (isDev) {
console.log(error)
}
})
})
}
}
I use in my react application redux saga. There i have a login form. With redux saga i try to handle the error when user login.
Bellow is my saga:
function* postLoginUserReq(user) {
const {name} = user.values.user;
try {
const data = yield call(() => {
return fetch("url", {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
}),
}).then(data => data.json()).then(response => {
userErrorLogIn(response.error) //here i check if appears an error
})
});
} catch (error) {
console.log(error);
}
}
Bellow is action creator:
export const userErrorLogIn = (error) => {
console.log(error) //the error message appears here
return {
type: USER_ERROR_LOGIN,
payload: error
};
};
Bellow is reducer:
case USER_ERROR_LOGIN: {
console.log(action.payload) //here the error message does not appears (why?)
return {
...state,
userIsLoggedError:action.payload,
}
}
Question: What could be the issue that i don't get the error in reducer?
You can use .catch for that -
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch("http://httpstat.us/500")
.then(handleErrors)
.then(response => console.log("ok") )
.catch(error => userErrorLogIn(error) );
https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
I am using react+redux.
I have a modal form with data and images and on success I need to close the modal else display error returned from redux. In the dispatch function I have 1 more callback function to store images to S3. I am returning promise from the redux-thunk but I keep getting "TypeError: Cannot read property 'then' of undefined".
Component
handleSubmit = e => {
e.preventDefault();
if(this.isFieldEmpty()){
this.setState({ message: "All fields are mandatory with at least 1 pic" });
return;
} else {
this.setState({ message: "" });
}
const data = {
name: this.state.name,
description : this.state.description,
points : this.state.points,
attributes : this.state.attributes,
images : this.state.images,
created_by: localStorage.getItem('id'),
}
this.props.createItem(data).then(() => {
this.hideModal();
})
}
const mapDispatchToProps = dispatch => {
return {
createItem: data => {
return dispatch(createItem(data))
},
};
};
Action
const saveItemImages = (images,successcb, failurecb) => {
if(images.length > 0){
const formData = new FormData();
for(var x = 0; x<images.length; x++) {
formData.append('image', images[x])
}
const token = localStorage.getItem('token');
fetch(`${backendUrl}/upload/item-images/`, {
method: "POST",
headers: {
'Authorization': `Bearer ${token}`
},
credentials: 'include',
body: formData
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
successcb(resData.imagesUrl);
});
}else{
res.json().then(resData => {
failurecb(resData.message);
})
}
})
.catch(err => {
console.log(err);
});
} else {
successcb([]);
}
}
export const createItem = data => { return (dispatch) => {
saveItemImages(data.images, imagesUrl => {
data.images = imagesUrl;
return fetch(`${backendUrl}/admin/createItem`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.token}`
},
credentials: 'include',
body: JSON.stringify(data)
})
.then(res => {
if(res.status === 200){
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_SUCCESS,
payload: resData
})
return true;
});
}else{
console.log("Save failed");
res.json().then(resData => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: resData.message
}
})
})
}
})
.catch(err => {
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: {
message: `Internal Error -- ${err}`
}
})
});
}, failedMessage => {
let payload = {responseMessage: failedMessage}
dispatch({
type: ADMIN_CREATE_ITEM_FAILED,
payload: payload
})
});
};
};
Thanks in advance for any help
You should return a Promise to create async flow for the action like this:
export const createItem = data => dispatch => new Promise((resolve, reject) => {
// do something was a success
resolve();
// do something was a fail
reject();
});
I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.
So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.
Here is a fetch POST example. You can do the same for DELETE.
function createNewProfile(profile) {
const formData = new FormData();
formData.append('first_name', profile.firstName);
formData.append('last_name', profile.lastName);
formData.append('email', profile.email);
return fetch('http://example.com/api/v1/registration', {
method: 'POST',
body: formData
}).then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
})
.catch(error => error);
Ok, here is a fetch DELETE example too:
fetch('https://example.com/delete-item/' + id, {
method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))
For put method we have:
const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
Example for someData, we can have some input fields or whatever you need:
const someData = {
title: document.querySelector(TitleInput).value,
body: document.querySelector(BodyInput).value
}
And in our data base will have this in json format:
{
"posts": [
"id": 1,
"title": "Some Title", // what we typed in the title input field
"body": "Some Body", // what we typed in the body input field
]
}
For delete method we have:
const deleteMethod = {
method: 'DELETE', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
// No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
In the url we need to type the id of the of deletion: https://www.someapi/id
Just Simple Answer.
FETCH DELETE
function deleteData(item, url) {
return fetch(url + '/' + item, {
method: 'delete'
})
.then(response => response.json());
}
Here is good example of the CRUD operation using fetch API:
“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW
Here is the sample code I tried for PATCH or PUT
function update(id, data){
fetch(apiUrl + "/" + id, {
method: 'PATCH',
body: JSON.stringify({
data
})
}).then((response) => {
response.json().then((response) => {
console.log(response);
})
}).catch(err => {
console.error(err)
})
For DELETE:
function remove(id){
fetch(apiUrl + "/" + id, {
method: 'DELETE'
}).then(() => {
console.log('removed');
}).catch(err => {
console.error(err)
});
For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.
Some examples:
async function loadItems() {
try {
let response = await fetch(`https://url/${AppID}`);
let result = await response.json();
return result;
} catch (err) {
}
}
async function addItem(item) {
try {
let response = await fetch("https://url", {
method: "POST",
body: JSON.stringify({
AppId: appId,
Key: item,
Value: item,
someBoolean: false,
}),
headers: {
"Content-Type": "application/json",
},
});
let result = await response.json();
return result;
} catch (err) {
}
}
async function removeItem(id) {
try {
let response = await fetch(`https://url/${id}`, {
method: "DELETE",
});
} catch (err) {
}
}
async function updateItem(item) {
try {
let response = await fetch(`https://url/${item.id}`, {
method: "PUT",
body: JSON.stringify(todo),
headers: {
"Content-Type": "application/json",
},
});
} catch (err) {
}
}
Let me simplify this, you can straight up copy the code.
This is for PUT method :
fetch('https://reqres.in/api/users', + id {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'user'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
and this is for DELETE :
fetch('https://reqres.in/api/users' + id, {
method: 'DELETE',
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Note: I'm using dummy api here.
This is what worked for me when using the PUT method. This method allows me to effectively update the 1st item using my first name:
fetch('https://reqres.in/api/users', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
first_name: 'Anthony'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:
Update (PUT):
export const updateProduct = (id, title, description, imageUrl) => {
await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
method: "PATCH",
header: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title,
description,
imageUrl,
}),
});
dispatch({
type: "UPDATE_PRODUCT",
pid: id,
productData: {
title,
description,
imageUrl,
},
});
};
};
Delete:
export const deleteProduct = (ProductId) => {
return async (dispatch) => {
await fetch(
`https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
{
method: "DELETE",
}
);
dispatch({
type: "DELETE_PRODUCT",
pid: ProductId,
});
};
};
const DeleteBtn = (id) => {
fetch(`http://localhost:8000/blogs/${id}`, {
method: "DELETE"
})
.then(() => {
navigate('/');
});
}
<button onClick={(event) => { DeleteBtn(blog.id)} }>delete</button>