Getting 429 (Too Many Request) in vue.js laravel - laravel

I'm using vue.js and laravel when i open edit page i get this error in my console but Update function is called on button click and bill url is also called multiple times without parameter on mounted function
app.js:1088 GET http://localhost:8000/api/userbackend/bill/undefined 404 (Not Found)
POST http://localhost:8000/api/userbackend/Update 429 (Too Many Requests)
Code Snippet:
async mounted(){
this.roleid = this.userData.role_id;
const header = {
'Authorization': 'Bearer ' + this.LoginUserData,
};
this.editId = this.$route.params.id;
if(this.$route.params.id !== undefined) {
try{
let response = await axios.get(`/api/userbackend/bill/${this.editId}` ,{headers: header});
this.form = response.data;
}
saveRecord(){
let loader = this.$loading.show();
let formData = new FormData();
formData.append('id', this.editId);
....
const header = {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + this.LoginUserData,
};
axios.post('/api/userbackend/Update', formData ,{headers: header}).then((response) =>{
loader.hide();
if(response.data.status == true){
.....
}
})
.catch((response) => {
loader.hide();
this.showErrorMsg();
});
},
validateBeforeSubmit(e) {
e.preventDefault();
let app = this;
this.$validator.validateAll().then((result) => {
if (result) {
app.saveRecord();
return;
}
this.showWarningMsg();
});
}
Any suggestion is highly appreciated

Related

How do I get the message using Office.js in a react add-in

I am building a new react Outlook add-in and need to be able to download the current email.
The Office.js API has the getFileAsync method off the Office.context.document object but not the Office.context.mailbox.item object.
also as a requirement this needs to work in both Office online and local installs of Outlook.
In the existing com add-in I had direct access to the mail item.
Here is the code that I currently have to call into the API, but this only retrieves metadata.
/*
https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api#get-the-item-id
*/
public getMessageViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId;
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.json().then((body) => {
for (const key in body) {
this.state.details.push({ name: key, value: JSON.stringify(body[key]) });
}
this.forceUpdate();
});
});
} catch (error) {
this.setState({ error: JSON.stringify(error) });
}
});
}
Its not perfect but the REST Api does have an end point that will return the file's EML contents.
public downloadViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId + '/$value';
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.blob().then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Message.eml';
a.click();
});
});
} catch (error) {
}
});
}

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

react-native fetch with authorization header sometime return 401

I'm facing some issue whereby I sometime will get status code 401 (Unauthorised) from my phone. I'm trying to access to an API from my computer localhost (192.168.0.7).
I've a screen, when I click on a button it will navigate to a page and it will request data through API. And when I go back and navigate to same page again, it sometime will return me code 401.
So if I repeat the same step (navigate and go back) let's say 10 times. I'm getting Unauthorised like 5-7 times.
Below are my code
export function getMyCarpool(param,token) {
return dispatch => {
var requestUrl = _api + 'GetMyProduct?' + param;
fetch(requestUrl, {
method: "get",
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + token
})
})
.then((request) => {
console.log(request);
if(request.status == 200)
return request.json();
else if(request.status == 401) {
//dispatch(logout());
throw new Error('Unauthorized access.');
}
else
throw new Error('Failed to request, please try again.');
})
.then((response) => {
var message = response.message;
if(response.success == 'true')
dispatch({ message, type: GET_MY_PRODUCT_SUCCESS });
else
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
})
.catch(error => {
var message = error.message;
dispatch({ message, type: GET_MY_PRODUCT_FAILED });
});
}
I've check the token in my phone and also trying to make many request using postman. So I don't think it's server side problem.
I'm using Laravel and using laravel passport for API authentication. I not sure why this happen if I continue to access many time, any help is greatly appreciated.
UPDATE :: I'm trying to capture whether the http request has the token from this link, and I don't get the problem anymore.
It's a healthy mechanism for token expire. Maybe you have your token (access_token) for 5 minutes, then the token expired, you should use refresh_token to regain another new token (access_token).
For code explanation:
async function fetchService(url) {
const reqSetting = {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${Auth.access_token}`,
},
};
const prevRequest = { url, reqSetting };
const resp = await fetch(url, reqSetting);
if (!resp.ok) {
const error = new Error(resp.statusText || 'Request Failed!');
if (resp.status === 401 || resp.status === 400) {
const responseClone = resp.clone();
const errorInfo = await resp.json();
if (errorInfo.error == 'invalid_token') {
// console.log('Token Expired', errorInfo);
try {
await refreshToken();
const response = await fetchService(prevRequest.url);
return response;
} catch (err) {
// handle why not refresh a new token
}
}
return responseClone;
}
error.errorUrl = url;
error.code = resp.status;
throw error;
}
return resp;
}
Where the refresh token function is :
async function refreshToken() {
const url = 'https://example.com/oauth/token';
const data = {
grant_type: 'refresh_token',
refresh_token: Auth.refresh_token,
};
try {
const res = await fetch(url, data);
const data = res.json();
Auth.access_token = data.access_token;
Auth.refresh_token = data.refresh_token;
return true;
} catch (error) {
throw error;
}
}
This fetchService will automatic regain a new token if old expired and then handle old request.
PS.
If you have multiple requests same time, the fetchService will need a little optimization. You'd better choose another regain token strategy like saga.

File upload with fetch API vuejs returns 419 unknown status

I am using VUE.js with Laravel to upload file using fetch api. I have added the csrf token to the header of the request, but still getting the 419 unknown status. Any help will be appreciated thanks.
Here is the JS of the component
<script>
export default {
name:'UploadModal',
data(){
return {
image:'',
ext:'',
file:''
};
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.file = files[0];
this.createImage(files[0]);
},
uploadArtwork: function () {
let formData = new FormData();
formData.append('artwork', this.file);
fetch(this.$parent.itemUrl, {
method:'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
'X-CSRF-TOKEN' : Laravel.csrfToken
}
})
.then(res => res.json())
.then(res => {
alert(res);
})
.catch(e => console.log(e));
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
}
}
</script>
I know this is an old question, but I ran into this issue as well when using fetch and the linked answer (Laravel 5.5 ajax call 419 (unknown status)) did not help, since that relates to jQuery's Ajax method.
For those who are facing the same issue, it looks like this is due to the default credentials setting (defaults to "omit"), which essentially omits the csrf header for some reason. You can get around this by changing credentials to "same-origin" or "include" depending on your needs.
Example:
fetch("/leads", {
method: 'POST',
credentials: "same-origin",
headers: csrf_header
}).then(res => res.json())
.then(
(json) => {
this.setState({
isLoaded: true,
items: json.leads.data,
sort: json.sort,
search: json.search,
sort_by: json.sort_by,
filter: json.filter
});
}
);

React-native : response of fetch impossible to treat

Still learning on RN... I'm trying to use fetch() in react-native to get a specific data from my server, before opening a webpage in smartphone's browser.
Here is what I wrote :
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
})
.done();
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
}
Actually, as you can see, I ask for a specific key to my server (urlKey, that is returned in a JSON Object : responseJson.document_key).
Everything is running well in server's part, cause I put this generated document_key in my Database, and I can see it is put correctly.
The problem is in React-native part : the browser opens a webpage with this.state.urlKey as **text** which is the initial state that the function fetch should have turned into the document_key sent by server...
What am I missing ?
The fetch statement is asynchronous. Meaning when you call fetch then next line of execution not necessary the .then but is
var urlString = Constants.URL.upload + '/' + this.state.urlKey;
Note by this stage if .then isnt complete fetching the data your this.state.document_key will not be populated. Hence why you see the error
Instead move that code in the final then e.g:
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
//moved inside then
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
})
.done();
}

Resources