I'm calling a payment gateway rest API to retrieve a QR code.
It works well in my local with ajax but impossible to make it work with axios on a firebase cloud functions (express on nodejs).
My ajax code in my local:
var dataReq = {
amount: '1',
referenceNo: 'chelou',
token:'myToken',
payType: 'F',
backgroundUrl: 'myBackgroundurl',
customerEmail: 'dgdfgdgdgd'
};
$.ajax({
type: "POST",
url: "https://api.gbprimepay.com/gbp/gateway/qrcode/text",
data: dataReq,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: function(dataResp){
console.log(dataResp)
},
failure: function(errMsg) {
console.log(errMsg);
}
});
});
My axios code in firebase cloud function:
axios({
method: 'post',
url: 'https://api.gbprimepay.com/gbp/gateway/qrcode/text',
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: {
amount: '1',
referenceNo: 'chelou',
token:'hW7RBDVpELvpxIJAxYf6AXl7ESXIWWOekGO/28aDCYkV7m07Fs26ko4QyROTFLNCZbRandtw5mxCgnQBtGdw5vYt5bkvmiZXi460Cc3yYWvNaE8LyEZJ1TdNJsX0poTwT9gb3hmy9JNdrxMB5HEwkjC9P18=',
payType: 'F',
backgroundUrl: 'https://us-central1-wyzauto.cloudfunctions.net/widgets/changeOrderStatus',
customerEmail: 'dgdfgdgdgd'
}
})
.then((response) => response.data)
.then((responseFinal) => {
return res.json(responseFinal);
})
.catch(error => {
return res.json({result: error});
})
});
The ajax code is returning
{referenceNo: "chelou", qrcode: "00020101021230830016A00000067701011201150105560068…chelou530376454041.005802TH5910GBPrimePay6304192E", resultCode: "00", gbpReferenceNo: "gbp352913431029"}
The axios code is returning {"resultCode":"90"} it's not an error but for some reason the qr code is not being computed
Do you see anything wrong with my header or something like that?!?
Related
There is an ajax script to remove comments under posts. When I click the delete button, I get a 405 error.
The console displays this: DELETE http://127.0.0.1:8000/id2/post/582 405 (Method Not Allowed), although the method is different url
My route Route::delete('/id{id}/post/{postId}/comment/{commentId}/delete', 'CommentController#deleteComment')->name('deleteComment');
And script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "DELETE",
data: {_token: token, id: id},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
I need that when I press delete, the record disappears, but it does not disappear. To make the entry disappear, you need to reload the page
Under the hood Laravel actually uses POST request within an _method as parameter when you perform destroy operation, so your JavaScript section should looks like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e) {
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "POST",
data: {_token: token, id: id, _method: 'DELETE'},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
Im using graphCMS and I want to make a post request using axios.
I can actually do a mutation in postman.
see example: https://prnt.sc/sjsj3p
but when in actual coding using axios, I cant get the proper format of the query.
I search some graphql mutation but it seems that the graphcms has a different format(Im not sure).
axios({
method: 'POST',
url: apiUrl,
headers: {
'Content-Type': 'application/json',
'Authorization': graphcmsBearerKey
},
data: {
query: `
mutation CreateCompanyCustomization() {
createCompanyCustomization(
data: {
domain: "sampledomain.com"
}
)
}
`
}
}).then(res => {
console.log(res)
}).catch(err => {
isErrorState('ERROR STATE')
console.log(err)
})
any suggestion? Thanks!
I have a React Component which calls an AJAX POST request.
The POST request creates an entry in the database as expected. (status 201 returned) However the success/error methods of the same are not called.
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend: function(xhr) {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success: function(data) {
console.log('success');
this.loadData();
},
error: function(xhr, status, err) {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});
The request is called through a button click. Also the browser hangs once the request is made, and the solution is to open a new tab.
Also i do not see the POST request on the Network tab of Chrome, but see it on the backend.
Any hints?
Try using ES6 arrow functions or bind your functions with this
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend:(xhr) => {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success:(data) => {
console.log('success');
this.loadData();
},
error:(xhr, status, err) => {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});
Can some one give me example of how to convert ajax to axios ?
I am trying to convert this code into axios
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
axios.post('http://example.com/storeauthcode', authResult['code'], {
headers: {
'X-Requested-With': 'XMLHttpRequest'
'Content-Type: 'application/octet-stream; charset=utf-8',
},
transformResponse: (data) => { // do something with your data },
});
However a better place for the content-type would be the axios instance config itself.
Configure once globally:
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Then per request:
const result = await axios.post(
'http://example.com/storeauthcode',
authResult['code'],
{
headers: {
'Content-type': 'application/octet-stream; charset=utf-8'
}
}
);
I am working on a Vue application with a seperate Laravel back-end API. The back-end has Laravel passport that requires an access token when doing database calls.
Normally everything goes right, I can get data back from the database but for some reason, 2 of my calls gets errors, the POST en PUT. I don't know why I get unauthenticated (401) from laravel passport back, while my get request is going well. Also, both POST and PUT are going fine in the postman application.
The get request
getSuppliers() {
axios.get(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
})
.then((response) => {
this.loaded = true;
this.relations = response.data.data;
})
.catch(error => console.log(error));
},
The post request
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
Helper functions for access token
function getHeaders(token) {
return {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
};
}
function getToken() {
const oauth = JSON.parse(localStorage.getItem('oauth') || '{}');
if (oauth.access_token) {
return oauth.access_token;
}
return false;
}
Somebody out there that had the same problem or similair?
After some digging, going through my other code and requests I find a solution that fixed it for me.
Instead of
axios.post(`${this.$API_URL}/api/v1/relations`, {
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I had to do
axios({
method: 'post',
url: `${this.$API_URL}/api/v1/relations`
headers: this.headers,
data: {
company_name: this.supplier.company_name,
language_id: this.supplier.language_id,
supplier_type_id: this.supplier.supplier_type_id,
email: this.supplier.email,
website: this.supplier.website,
recognition_number: this.supplier.recognition_number,
street: this.supplier.street,
house_number: this.supplier.house_number,
zipcode: this.supplier.zipcode,
city: this.supplier.city,
country: this.supplier.country,
},
})
.then((response) => {
console.log(response);
// retrieve the id
// push the user to the show of the retrieved id
})
.catch(error => console.log(error));
I don't see any difference except the style, so I don't know exactly why the second style is working and the first one is not, especially for the put and post type of requests.