I have a problem with GraphQL. I want to send axios.post request to my server. I can do it in postman:
{ "query":"mutation{updateUserCity(userID: 2, city:\"test\"){id name age city knowledge{language frameworks}}} " }
and in graphiql:
mutation { updateUserCity(userID: 2, city: "test") { id name age city knowledge { language frameworks } } }
but can't do it in my code:(( here is my code snippet:
const data = await axios.post(API_URL, { query: mutation updateUserCity(${ id }: Int!, ${ city }: String!) { updateUserCity(userID: ${ id }, city: ${ city }){ id name age city knowledge{ language frameworks } } } }, { headers: { 'Content-Type': 'application/json' } })
what's wrong in my code?
Yes! This is very similar to how you make REST API calls. The only part which you need to worry about is constructing the query object of the GraphQL Query. Now let us look at the same example with Axios.
GraphQL requests can be sent via HTTP POST or HTTP GET requests. GET requests must be sent in the following format. The query, variables, and operation are sent as URL-encoded query parameters in the URL. In either request method (POST or GET), only query is required.
You can fetch data very simply with the help of the package graphql-request . GraphQL Request is a library that doesn't require you to set up a client or a Provider component. It is essentially a function that just accepts an endpoint and a query.
Unfortunately, while I'm sure their platform is great, if you're setting up a fresh GraphQL API you should not start with Apollo. It certainly might be useful later, but on day 1 it's a trap, and you'll make your life simpler and easier if you avoid it entirely.
Value of query
parameter to be passed in request has to be string and names of variables passed to GraphQL queries should be prefixed by $
. You have used string literals for variables in request instead. Also, variables can be passed in post request using variables
key.
Changing your code to something like below should get it to working:
const data = await axios.post(API_URL, { query: `mutation updateUserCity($id: Int!, $city: String!) { updateUserCity(userID: $id, city: $city){ id name age city knowledge{ language frameworks } } }`, variables: { id: 2, city: 'Test' } }, { headers: { 'Content-Type': 'application/json' } })
I enjoy using the following syntax, which is similar to the accepted answer, but more explicit.
Note that the variables
object is nested inside of the data
object, and is a sibling of the query
object.
const data = await axios({ url: API_URL, method: 'post', headers: { 'Content-Type': 'application/json', // any other headers you require go here }, data: { query: ` mutation updateUserCity($id: Int!, $city: String!) { updateUserCity(userID: $id, city: $city){ id name age city knowledge{ language frameworks } } } `, variables: { id: 2, city: 'Test' } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With