GRAPHQL mutation with axios - graphql

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!

Related

Passing array from POSTMAN and AJAX is different when received by ExpressJS

I am new to Express but not in programming. I am trying to pass an array via ajax from my frontend to express. On my postman, this is the array I am sending:
{
"userIds": ["xxxxxxxxxxxxxxxxxx"],
"type": "user"
}
and express is receiving req.body as:
{
userIds: [ 'xxxxxxxxxxxxxxxxxx' ],
type: 'user'
}
When I do this in Ajax:
data = {
userIds: ["xxxxxxxxxxxxxxxxxx"],
type: "user",
};
$.ajax({
type: "POST",
url: url,
headers: headerParams,
data: data,
success: function (room) {
console.log("room", room);
},
error: function (error) {
console.log("error", error);
},
});
Express is receiving:
[Object: null prototype] {
'userIds[]': 'xxxxxxxxxxxxxxxxxx',
type: 'user'
}
What am I doing wrong here? Or how should I mutate my req.body to get the desired output?
Note: I cannot do req.body.Foreach since it is saying forEach is not a function.
Note 2: req.body.userIds returns undefined
My best guess, Middleware body-parser to your rescue.
You can then access it as req.body.userIds, which will be an Array.

axios request on google cloud functions using express

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?!?

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

Get a 401 error with POST and PUT Laravel passport/Vue/Axios

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.

React Native getting response 400 when post to oauth/token using laravel passport

I am trying to login through oauth/tokens from my React Native project. I have tested with POSTMAN When i send the data from axios it works well. But when i try to send from my app it gives me Error: Request failed with status code 400
my code is :
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: {
client_id : '2',
client_secret : 'secret',
grant_type : 'password',
email : this.state.userEmail,
password : this.state.userPassword
}
})
.then((response) => {
console.log(response.data);
})
I've solved the problem in this way:
axios({
method: 'post',
url: 'http://183.172.100.84:8000/oauth/token',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
data: 'client_id=2&client_secret=secret&grant_type=password&email=' + this.state.userEmail+'&password='+this.state.userPassword
})
.then((response) => {
console.log(response.data);
})
Seems Axios have some problem to process the data in json format.
If you use Webpack you must also configure the proxy.

Resources