graphql.js icon indicating copy to clipboard operation
graphql.js copied to clipboard

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

Open mrkhan opened this issue 4 years ago • 6 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

mrkhan avatar May 02 '20 15:05 mrkhan

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!

chiubaca avatar May 04 '20 19:05 chiubaca

Hey!

Can you test is by passing asJSON: true?

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

f avatar May 05 '20 07:05 f

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.

chiubaca avatar May 05 '20 07:05 chiubaca

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.

f avatar May 05 '20 08:05 f

gotcha, thanks for clarifying.

sorry for hijacking your issue @mrkhan!

chiubaca avatar May 05 '20 08:05 chiubaca

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.

mrkhan avatar May 06 '20 08:05 mrkhan