JSON Parse error occurs in "expo-auth-session"

84 Views Asked by At

I am developing Twitter authentication with ReactNative. I am using the "expo-auth-session" library. When executing "tokenRequest.performAsync(discovery)" with the code below, the following error occurs. What is the cause?

SyntaxError: JSON Parse error: Unexpected character: <

import {makeRedirectUri, useAuthRequest, AccessTokenRequest} from 'expo-auth-session';

...

const discovery = {
  authorizationEndpoint: "https://twitter.com/i/oauth2/authorize",
  tokenEndpoint: "https://twitter.com/2/oauth2/token",
  revocationEndpoint: "https://twitter.com/i/oauth2/revoke",
};

const reqConfig = {
  clientId: TWITTER_CLIENT_ID,
  clientSecret: TWITTER_CLIENT_SECRET,
  redirectUri: makeRedirectUri({
    scheme: 'xx.xx.xx',
    path: 'twitter/callback',
  }),
  usePKCE: true,
  scopes: [
    'tweet.read',
    'tweet.write',
    'offline.access',
  ],
};

const [request, response, promptAsync] = useAuthRequest(
  {...reqConfig},
  discovery,
);

useEffect(() => {
  if (response?.type === 'success') {
    const {code, state} = response.params;

    const tokenRequest = new AccessTokenRequest({
      ...reqConfig,
      code,
      extraParams: {
        code_verifier: request.codeVerifier,
        state,
      },
    });

    (async() => {
      try {
        const tokenResult = await tokenRequest.performAsync(discovery);
      } catch (e) {
        console.log(e);
      }
    })();
  }
}, [response]);

return (
  <View>
    <Button onPress={() => promptAsync} title={'login'}></Button>
  </View>
);
1

There are 1 best solutions below

1
tr0yspradling On

Just based off JSON Parse error: Unexpected character: < it looks like HTML is being parsed as JSON. When this happens double check any HTTP endpoints and make sure the Content-Type header is being passed.

See if you can dump the response object into a log, and also take a look at what's defined in tokenRequest before calling performAsync.

This looks related: Cannot authenticate with Twitter using Expo