When I try to send data via axios with query data. Looks like the problem is with JSON.stringify, it returns incorrect data to be able to send.
Is there any solution to this problem?
var axios = require('axios');
var data = JSON.stringify({
query: `mutation { flowTriggerReceive(body: "{ \"trigger_id\": \"28a17088-92d7-42e7-a1f2-3594fc4b8bf9\", \"resources\": [ { \"name\": \"AppName\", \"url\": \"https://app.doman.com\" } ], \"properties\": { \"product_id\": 3665695899753, \"Rating\": 5, \"Author\": \"John Kendy\", \"Email\": \"cauhaibg#gmail.com\", \"Country Code\": \"VN\" } }") { userErrors { field, message } } }`,
variables: {}
});
//console.log(data);
var config = {
method: 'post',
url: 'https://{shop_domain}/admin/api/2023-01/graphql.json',
headers: {
'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Get error
{"errors":[{"message":"Parse error on \": \" (STRING) at [1, 51]","locations":[{"line":1,"column":51}]}]}
Note that you do not need to serialize the data object to JSON as Axios will automatically do it for you. Try to send the data object "as is" without stringify it first
var axios = require('axios');
var data = {
query: `mutation { flowTriggerReceive(body: "{ \"trigger_id\": \"28a17088-92d7-42e7-a1f2-3594fc4b8bf9\", \"resources\": [ { \"name\": \"AppName\", \"url\": \"https://app.doman.com\" } ], \"properties\": { \"product_id\": 3665695899753, \"Rating\": 5, \"Author\": \"John Kendy\", \"Email\": \"cauhaibg#gmail.com\", \"Country Code\": \"VN\" } }") { userErrors { field, message } } }`,
variables: {}
};
var config = {
method: 'post',
url: 'https://{shop_domain}/admin/api/2023-01/graphql.json',
headers: {
'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
},
data : data
};
Related
I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request
I am trying to fetch a contact in JobNimbus based on their display name. According to their docs under "Retrieve All Contacts", I should be able to do this.
Below is the code they recommend:
var axios = require('axios');
var config = {
method: 'get',
url: 'https://app.jobnimbus.com/api1/contacts',
headers: {
'Authorization': 'bearer <token>',
'Content-Type': 'application/json'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Below is their request parameters example:
{
"must": [
{
"range": {
"date_created": {
"gte": 1459749600,
"lte": 1459835940
}
}
}
]
}
How do I request a contact based on their display_name?
It explains how to filter your search in the docs here. Just have to include the search criteria in the query params.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://app.jobnimbus.com/api1/contacts?filter={"must":[{"term":{"first_name":"John"}},{"term":{"last_name":"Smith"}}]}
',
headers: {
'Authorization': 'bearer <token>',
'Content-Type': 'application/json'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
I'm trying to hit the Intercom API to retrieve a list of conversations and I can't figure out what's wrong. Here is the code:
const request=require('request')
const search_intercom=(admin_id, callback) => {
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: {
query: JSON.stringify({
"field": "teammate_ids",
"operator": "=",
"value": admin_id
})
}
};
request(options, (error, {body} = {}) => {
if (error) {
callback('unable to connect to intercom API', undefined)
} else if (body.length === 0) {
callback('something went wrong', undefined)
} else {
callback(undefined, {
conversation_id: body.conversations[0].id,
client_name: body.conversations[0].source.author.name
})
console.log(body)
}
})
}
module.exports = search_intercom
I was able to wire it up correctly with the web server, so when I debug, options.json.query.admin_id does contain a valid id.
It breaks and says
conversation_id: body.conversations[0].id,
TypeError: Cannot read property '0' of undefined
Here is the content of the body response:
{
type: 'error.list',
request_id: '<some request_id>',
errors: [ { code: 'server_error', message: 'Server Error' } ]
}
Where should I look? I've tried a few different variations of options for sending the payload and I am guessing this is the issue, but I can't find the winning formula...
It looks like I got the body all wrong.
options should look like this instead:
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: true,
body: {
query: {
"field": "teammate_ids",
"operator": "=",
"value": JSON.stringify(admin_id)
}
}
};
I'm successfully authenticating with the server, sending my graphql request and receiving a response. However the response isn't quite right.
This is just a simple nodejs, axios, graphql situation. I can get a correct respose via postman or curl but not with node. I've tried fetch as well to no avail. Am I doing something wrong? This is for the producthunt api, the api explorer is located at here
require('dotenv').config()
const axios = require("axios");
const PH_KEY = process.env.PH_KEY;
const PH_SECRET = process.env.PH_SECRET;
const BASE_URL = process.env.BASE_URL;
const AUTH_URL = process.env.AUTH_URL;
const GRAPHQL_URL = process.env.GRAPHQL_URL;
const PH = axios.create({
baseURL: BASE_URL,
responseType: 'json',
headers: {
// 'Accept': 'application/json, text/plain, gzip, deflate, */*',
'Content-Type': 'application/json'
},
})
let TOKEN = 'Bearer '
const getAuth = async () => {
return await PH({
url: AUTH_URL,
method: "post",
data: {
client_id: `${PH_KEY}`,
client_secret: `${PH_SECRET}`,
grant_type: "client_credentials"
}
})
.then((res) => {
console.log('auth status ', res.status)
return res.data.access_token
})
.then((res) => {
TOKEN += res
console.log(TOKEN)
})
.catch((err) => {
console.log(err)
})
}
const getHunt = async () => {
await getAuth()
PH.defaults.headers.common['Authorization'] = TOKEN
return await PH({
url: GRAPHQL_URL,
method: 'post',
data:
{
query: `
query posts {
posts(order: RANKING, first: 1) {
edges {
node {
name
votesCount
user {
name
}
createdAt
}
}
}
}
`
}
})
.then((res) => {return res})
.then((res) => {
console.log(res.data)
return res.data
})
.catch((err) => {
console.log(err)
})
}
const Main = async () => {
await getHunt()
}
Main()
This is the output I receive in node:
[Running] node "/Users/fireinjun/Work/YAC/yac-ph-tophuntfunction/app.js"
auth status 200
Bearer #################################################
{ data: { posts: { edges: [Array] } } }
Here's what I'm expecting:
{
"data": {
"posts": {
"edges": [
{
"node": {
"name": "Trends by The Hustle",
"votesCount": 125,
"user": {
"name": "Jack Smith"
},
"createdAt": "2019-06-04T07:01:00Z"
}
}
]
}
}
}
I was accessing the data incorrectly! Apparently I needed to see the res.data.data.posts.edges[0]
Thank you guys cause reading my question. The title is exactly what i wanna known.
Hope it do not cost your time much.
Some of the most common graphql client are graphql.js and apollo-client. You can also use the popular request module. The graphql API is a single POST endpoint on https://api.github.com/graphql with a JSON body consisting of the query fields and the variables fields (if you have variables in the query)
Using graphql.js
const graphql = require('graphql.js');
var graph = graphql("https://api.github.com/graphql", {
headers: {
"Authorization": "Bearer <Your Token>",
'User-Agent': 'My Application'
},
asJSON: true
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`)({
name: "linux",
owner: "torvalds"
}).then(function(response) {
console.log(JSON.stringify(response, null, 2));
}).catch(function(error) {
console.log(error);
});
Using apollo-client
fetch = require('node-fetch');
const ApolloClient = require('apollo-client').ApolloClient;
const HttpLink = require('apollo-link-http').HttpLink;
const setContext = require('apollo-link-context').setContext;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const gql = require('graphql-tag');
const token = "<Your Token>";
const authLink = setContext((_, {
headers
}) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
});
const client = new ApolloClient({
link: authLink.concat(new HttpLink({
uri: 'https://api.github.com/graphql'
})),
cache: new InMemoryCache()
});
client.query({
query: gql `
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`,
variables: {
name: "linux",
owner: "torvalds"
}
})
.then(resp => console.log(JSON.stringify(resp.data, null, 2)))
.catch(error => console.error(error));
Using request
const request = require('request');
request({
method: 'post',
body: {
query: `
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
} `,
variables: {
name: "linux",
owner: "torvalds"
}
},
json: true,
url: 'https://api.github.com/graphql',
headers: {
Authorization: 'Bearer <Your Token>',
'User-Agent': 'My Application'
}
}, function(error, response, body) {
if (error) {
console.error(error);
throw error;
}
console.log(JSON.stringify(body, null, 2));
});