How to use fetch() to send GraphQL queries to GraphQLJS - node.js

I've been having trouble sending GraphQL queries to my GraphQLJS backend, I copy and pasted the query that I use in GraphiQL (that works fine) but it's causing a syntax error: {"errors":[{"message":"Syntax Error: Expected :, found String \": \"","locations":[{"line":2,"column":45}]}]}
graphQLTest = async () => {
var data = {
query: `mutation {
createAuctionOffering(features:"{\"year\": \"2002\", \"model\":{\"make\":\"honda\", \"selectedModel\":\"civic\"}}", start_time:"2019-03-15 19:05:45.109+00", duration:"2019-03-15 19:05:45.109+00"){
auc_id
}
}`,
}
// data = await JSON.stringify(data)
var token = jwt.sign({name:data}, 'LIdXNnmK2qJNyTGs456bR0iebf9eGZV7', {expiresIn: '10s'});
let response = await fetch('http://localhost:8000/graphql', {
method: 'post',
headers: {
"User": "charlesdsmith25#gmail.com",
"Content-Type": "application/json"
},
body: JSON.stringify({name:token})
})
let jsonResponse = await response.text()
console.log(jsonResponse)
}
I've also been using JWT but that isn't an issue seeing as the query makes it through to the backend and raises the syntax error. This is the query I'm trying to send:
var data = {
query: `mutation {
createAuctionOffering(features:"{\"year\": \"2002\", \"model\":{\"make\":\"honda\", \"selectedModel\":\"civic\"}}", start_time:"2019-03-15 19:05:45.109+00", duration:"2019-03-15 19:05:45.109+00"){
auc_id
}
}`,
}
It seems like the problems lies with the quotes

Related

Passing Step Function in Node.JS

In Pipedream, I have an OpenWeatherAPI request that successfully retrieves forecast data for temperature on a given day.
My goal is to send this forecast to send a PUT request to a service called Apilio that stores a temperature value for further evaluation.
I’m able to conduct the GET and PUT HTTP requests respectively, but unable to pass the data within Pipedream. In other words, I can manually type in a temperature value in the PUT request, but unable to pass it as a variable.
Here is my script thus far:
import axios from "axios"
export default defineComponent({
async run({ steps, $ }) {
const feelslikeresponse =
steps.OpenWeatherAPI.$return_value.daily[7].feels_like.morn;
return feelslikeresponse;
const { data } = await axios({
method: "PUT",
url: "https://api.apilio.com/api/v1/numeric_variables/(my UUID)",
})
return data.species
}, })
var data = { "numeric_variable": { "value": feelslikeresponse } };
let config = {
"method": 'put',
"url": 'https://api.apilio.com/api/v1/numeric_variables/(my UUID)',
"headers": {
'Content-Type': 'application/json',
'Authorization': 'Basic (my header code)'
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
Within the code preview, I am able to hover over steps.OpenWeatherAPI.$return_value.daily[7].feels_like.morn and see the temperature value, but subsequent references to it are lost.
I am still new to coding and would appreciate any pointers or guidance.
Thanks to Wesley for the lesson and scrutinizing syntax. Between this and some hints from the Pipedream forums, how Axios works, and other documentation, I worked out the solution as follows:
import {axios} from "#pipedream/platform";
export default defineComponent({
async run({ steps, $ }) {
const feelslikeresponse =
steps.OpenWeatherAPI.$return_value.daily[7].feels_like.morn;
let data = JSON.stringify({
"numeric_variable":{
"value":feelslikeresponse
}
})
const { config } = await axios($,{
method: "put",
url: "(myUUID)",
headers: {
"Content-Type": "application/json",
Authorization:
"Basic (headercode)",
},
data : data
});
return feelslikeresponse;
},
});

Somebody knows how to solve 401 Unauthorized error with Clockify API using axios and node js

Does someone know why I'm getting a 401 Unauthorized error when I try to post a request to add a time entry even though I have added my API key?
I'm using Axios and node js, and this is the information and how I am making the request. However, I am able to get a list of users using the axios.get() method with the same API key, so I'm not sure why the post request says I'm not Unauthorized.
const insertOwnTimeEntryUrl = `${url}/workspaces/${workspaceId}/time-entries`;
let payload = {
start: "2022-05-05T17:10:00.000Z",
billable: "true",
description: "Test insert 1",
projectId: projectIdToInsert,
taskId: taskIdToInsert,
end: "",
tagIds: [tagIdToInsert],
};
let headers = {
"X-Api-Key": key,
};
let clockifyData = {
headers,
payload,
};
async function addNewEntry(clockifyData, insertOwnTimeEntryUrl, key) {
return (response = await axios
.post(`${insertOwnTimeEntryUrl}`, {
data: clockifyData.payload,
headers: {
"X-Api-Key": key,
"Content-Type": "application/json",
},
})
.catch(function (error) {
console.log(error.response.data.message);
return;
}));
}
addNewEntry(clockifyData, insertOwnTimeEntryUrl, key);

Nodejs - Axios not using Cookie for post request

I'm struggling with AXIOS: it seems that my post request is not using my Cookie.
First of all, I'm creating an Axios Instance as following:
const api = axios.create({
baseURL: 'http://mylocalserver:myport/api/',
header: {
'Content-type' : 'application/json',
},
withCredentials: true,
responseType: 'json'
});
The API I'm trying to interact with is requiring a password, thus I'm defining a variable containing my password:
const password = 'mybeautifulpassword';
First, I need to post a request to create a session, and get the cookie:
const createSession = async() => {
const response = await api.post('session', { password: password});
return response.headers['set-cookie'];
}
Now, by using the returned cookie (stored in cookieAuth variable), I can interact with the API.
I know there is an endpoint allowing me to retrieve informations:
const readInfo = async(cookieAuth) => {
return await api.get('endpoint/a', {
headers: {
Cookie: cookieAuth,
}
})
}
This is working properly.
It's another story when I want to launch a post request.
const createInfo = async(cookieAuth, infoName) => {
try {
const data = JSON.stringify({
name: infoName
})
return await api.post('endpoint/a', {
headers: {
Cookie: cookieAuth,
},
data: data,
})
} catch (error) {
console.log(error);
}
};
When I launch the createInfo method, I got a 401 status (Unauthorized). It looks like Axios is not using my cookieAuth for the post request...
If I'm using Postman to make the same request, it works...
What am I doing wrong in this code? Thanks a lot for your help
I finally found my mistake.
As written in the Axios Doc ( https://axios-http.com/docs/instance )
The specified config will be merged with the instance config.
after creating the instance, I must follow the following structure to perform a post requests:
axios#post(url[, data[, config]])
My requests is working now :
await api.post('endpoint/a', {data: data}, {
headers: {
'Cookie': cookiesAuth
}
});

Getting LinkedIn access token through http request on node.js server

I am following the Authorization Code Flow (3-legged OAuth) documentation and I am now at step 3 where I need to use the authorization code in order to recieve an access token from LinkedIn. In the project I am using node.js, typescript and the node-fetch library. The following function creates a body with content type x-www--form-urlencoded since this is content type which LinkedIn require.
async function GetAccessToken(data: any) {
let body: string | Array<string> = new Array<string>();
for (let property in data) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(data[property]);
body.push(encodedKey + "=" + encodedValue);
}
body = body.join("&");
const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: body
}).then((res: any) => {
console.log("Result", res);
});
return response;
}
I do not recieve any errors and the response status is 200 but the response values I recieve are:
size: 0,
timeout: 0,
and what LinkedIn promise is:
access_token
expires_in
When I post the url with my parameters using postman the request goes through and I recieve the correct data which indicates the problem lies within my request function and not my values.
Any help is appreciated!
You need add all headers from postman
const urlencoded = new URLSearchParams();
urlencoded.append("client_id", env.LINKEDIN_CLIENT_ID);
urlencoded.append("client_secret",env.LINKEDIN_CLIENT_SECRET);
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append(
"redirect_uri",
"http://localhost:3000/api/auth/linkedin-custom"
);
const accessTokenPromise = await fetch(
"https://www.linkedin.com/oauth/v2/accessToken",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: urlencoded,
}
);

PUT doesn't work on POSTMAN but okay when called from front-end

I have the following lambda function that works when called from the front-end React app:
// Update a contact
module.exports.updateContact = async (event, _context) => {
const id = event.pathParameters.id;
const body = JSON.parse(event.body);
const paramName = body.paramName;
const paramValue = body.paramValue;
const params = {
Key: {
id: id
},
TableName: contactsTable,
ConditionExpression: 'attribute_exists(id)',
UpdateExpression: 'set ' + paramName + ' = :v',
ExpressionAttributeValues: {
':v': paramValue,
},
ReturnValues: 'ALL_NEW'
};
try {
const res = await db.update(params).promise();
}
catch (err){
console.log(err);
return err;
}
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
status: 'updated!',
[paramName]: paramValue,
}),
};
return response;
};
But it fails with status code 502 & 'InternalServerErrorException' message when called from Postman.
I tried to solve it with one of the suggestions found on stackoverflow with method override:
It doesn't work and I'm now getting status code 403 and 'MissingAuthenticationTokenException'.
I'm not sure what I'm doing wrong, seeking some guidance. Thank you.
It seems the API endpoint has an Authorizer configured on the API Gateway and the front end is sending the correct credentials, while the Postman configuration is not.
I would suggest to use the browser dev tools selecting the PUT request and copy it as cUrl:
then you can paste the copied cUrl command into the Postman request. It will prefill all the parameters: method, body and the headers.
hope this help

Resources