I am currently using GraphQL Server and axios for client side.
I would like to know how to call this graphQL to my axios
mutation {
createUser(email: "hello#gmail.com") {
email
}
}
How can I call it like this?
const res = await axios.get('http://localhost:5000/public?query={users{email}');
You need to use post method to send your query/mutation to the GraphQL server:
axios({
// Of course the url should be where your actual GraphQL server is.
url: 'http://localhost:5000/graphql',
method: 'post',
data: {
query: `
mutation createUser($email: email){
createUser(email: $email) {
email
}
}`,
variables: {
email: "hello#gmail.com"
}
}
}).then((result) => {
console.log(result.data)
});
Related
I have:
rules={{
required: 'This is required.',
validate: (value) => daoExists(value),
}}
with daoExists, I need to check GraphQL endpoint and if it returns true, validation succeeds, otherwise some error message. I am using useQuery hooks from Apollo client for such queries, but now I have a problem, because daoExists can't be a hook. So, what I am doing is I create a daoExists as normal function. Something like this:
export const daoExists = async (name: string): Promise<ValidateResult> => {
const query = `
query Daos($name: String) {
daos(where: {name: $name}){
id
}
}
`;
const data = await fetch(subgraphUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query,
variables: { name: name },
}),
});
const daos = await data.json();
return daos?.data?.daos?.length > 0 || 'Dao with this name already exists';
};
Which I really don't like to use fetch and I want to continue using useQuery hooks, but I can't. I even tried creating useCallback, but then I can't use useQuery in my useCallback.
Are there any workarounds?
I have the following method from my vuex action block where I send user email and password to backend server and get userId and token on success.
async signIn ({ commit }, formData) {
const graphqlQuery = {
query: `
query{
loginData(
email: "${formData.email}",
password: "${formData.password}"
) {userId, token}
}
`
}
const res = await this.$axios.post('http://localhost:8080/graphql', graphqlQuery, {
headers: {
'Content-Type': 'application/json'
}
})
console.log(res.data) //works
console.log(res.data.loginData.token) //doesn't work
commit('loadUserData', true, res.data.loginData.token, res.data.loginData.userId)
return res.status
}
I can confirm that I'm getting the response data with console.log(res.data). The response data I get is:
But when I console.log(res.data.loginData) I get undefined. And blank on console.log(res.data.loginData.token) and console.log(res.data.loginData.token).
How do I extract the required data token and userId ?
I'm using webstorm as my IDE and it shows loginData as method refering to my backend graphql resolver method.
My frontend is made on Nuxt js, backend on node js with graphql.
Does anyone have any idea to overcome this issue ?
I am trying to use Axios post to create a user in my Django Rest Framework api.
Currently getting "Request failed with status code 400" when trying to post.
It works perfectly fine in postman.
drfServer.js
import axios from 'axios';
export default axios.create({
baseURL: 'https://example.com'
});
AuthContext.js
const signup = (dispatch) => async ({ email, password }) => {
try {
const response = await drfApi.post('/user/',
{
data: {
username: email,
password: password
}
}
);
// await AsyncStorage.setItem('token', response.data.token);
// dispatch({ type: 'signin', payload: response.data.token });
// navigate('Task')
} catch (err) {
console.log(err.message)
dispatch({ type: 'add_error', payload: 'Something went wrong with sign up' })
}
};
I tried using fetch and it works. But with Axios I am not getting it right.
Any ideas how to make it work?
Can you try this code.
const signup = ({email,password}) => dispatch => {
return axios({
method: "post",
url: "your api url",
data: {
username: email,
password
})
.then(result => {
console.log(result.data);
})
.catch(error => {
console.log(error);
})
};
You can find the axios example code here https://github.com/axios/axios
Maybe you can try this :
const response = await drfApi.post('/user/', {
username: email,
password: password
}
);
As using axios.post will automatically take the 2nd param and make it an object with data key
I am struggling to execute my first graphQl query with axios.
The app stack is Gatsby on the front-end with Symfony's API-Platform on the back end.
I did check a few the other similar questions at SO and blog posts but no luck.
The thing is that the query works on graphiQl AND it also works if I attempt to execute with fetch API.
This code is within sagas.js
Here's the
const api = (data) => {
return axios({
method: 'POST',
url: API_ROOT_GRAPHQL,
data,
headers: { 'Content-Type': 'application/json' },
}).then((response) => {
console.log('response axios', response);
return response.data;
});
};
function* getUserProfile(action) {
const userId = `"/api/users/${action.payload.userId}"`;
const queryQl = {
query: `{
user(id: ${userId}) {
id
username
name
email
roles
}
}`,
};
try {
yield put({
type: GET_USER_PROFILE_INIT,
});
const data = yield call(api, queryQl);
console.log('data user profile', data);
yield put({
type: GET_USER_PROFILE_OK,
data: data.user,
});
} catch (error) {
As you can see below is throws error: Cannot return null for non nullable field
Thing is that the below fetch query works perfectly - as does graphiql - so I am wondering this must be some config issue on my axios request.
I also checked that the data posted to the API with the same with both axios et fetch, as below from Firefox dev tools Network-> params:
query { user(id: "/api/users/1") { id username name email roles } }
const apiQl = (queryQl) => {
return fetch('http://localhost:8000/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(queryQl),
}).then((response) => {
return response.json();
}).then((response) => {
console.log('rsponse fetch', response);
return response.data;
});
};
EDIT: request header for axios
As both graphiQl and fetch() were working and axios was not, I was quick to point fingers at the latter. As it happens axios was the only one working properly.
As #coreyward suggested, there were restrictions on the server side, so that some User properties should only be available for query by their user owner, and username was not among them.
For those familiar with Symfony's API-Platform:
As an example, the email property was available, as it included the get-owner annotation.
/**
* #ORM\Column(type="string", length=180)
* #Groups({"post", "put", "get-admin", "get-owner"})
* #Assert\NotBlank(groups={"post"})
* #Assert\Email(groups={"post", "put"})
* #Assert\Length(min=6, max=180, groups={"post", "put"})
*/
private $email;
But username did not include the get-owner group annotation:
/**
* #ORM\Column(type="string", length=180)
* #Groups({"post", "get-ad-with-user"})
* #Assert\NotBlank(groups={"post"})
* #Assert\Length(min=6, max=50, groups={"post"})
*/
private $username;
So the fix was just to add that annotation to the username property as so:
* #Groups({"post", "get-ad-with-user", "get-owner"})
It is unclear to me at this time on why did fetch() and graphiQl were able to fetch the data.
I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).
This is the post method :
.post(`/mails/users/sendVerificationMail`, {
mail,
firstname
})
.then(response => response.status)
.catch(err => console.warn(err));
(my mail and firstname are console.logged as follow: lol#lol.com and myFirstName).
So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "lol#lol.com", firstname: "myFirstName" }.
axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
You can use params and body together in a request with axios
sendAllData (data) {
return axios
.post(API_URL + "receiveData", JSON.stringify(data), {
headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { mail: xyx#example.col }, //Add mail as a param
})
.then((response) => console.log("repsonse", response.status));
}