f / graphql.js

A Simple and Isomorphic GraphQL Client for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

POST body missing. Did you forget use body-parser middleware?

mrkhan opened this issue · comments

Hi,

Has anyone faced this issue

POST body missing. Did you forget use body-parser middleware?

SyntaxError: Unexpected token P in JSON at position 0
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/home/abc/server/node_modules/graphql.js/graphql.js:71:25)

this is my code

const query = graph(`mutation(
    $username: String!, 
    $password: String! ) {
      authentication {
      login(
        username: $username,
        password: $password,
        strategy: "local"
      ) {
        responseResult {
          succeeded
          errorCode
          message
        }
        jwt
      }
    }
  }`);

  query({
    username: req.body.username,
    password: req.body.password
  }).then(
    resData => {
      res.send(resData);
    },
    err => {
      console.error(err)
      res.status(500).send(err)
    }
  );

am running graphql.js in express server and not using 'body-parser' but rather uses express.json(). I am sure that I am able to read 'req.body.username' and 'req.body.password' values successfully, so why is it suggesting to use body-parser ?

Weird thing is this request runs fine on my local machine but gives this error on deployed server.

Could someone let me know, how to console.log body, before we query?

Regards

Hi @mrkhan, i'm running into the same error. I'm quite new to GraphQL and this library. But i'm trying to learn how it all works with this free GraphQL API here - https://countries.trevorblades.com/

I've made a JSfiddle which reproduces the error - https://jsfiddle.net/21f75w9e/9/ .

I hope someone can help!

Hey!

Can you test is by passing asJSON: true?

const graphTest = graphql("https://countries.trevorblades.com/", {
  method: "POST",
  asJSON: true
});

Thanks @f , that did the trick, in my example!

What exactly does that parameter do? I'm reading the README and I'm still a bit confused.

As default, GraphQL.js makes a POST request. But you can change the behavior by setting asJSON.

It converts Form data to JSON body. Normally it sends data as form values. If you're using a back-end which uses JSON body it may break.

gotcha, thanks for clarifying.

sorry for hijacking your issue @mrkhan!

In my case, my client don't directly query graphql server. I am able to read each values (username, password) in my node server which then fires query to Graphql.