Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: SyntaxError: JSON.parse: bad parsing #22837

Closed
wants to merge 1 commit into from
Closed

Conversation

rgbkids
Copy link

@rgbkids rgbkids commented Nov 27, 2021

Summary

There was a bug in packages/react-fetch/src/ReactFetchNode.js.
It's the usage of JSON.parse().

SyntaxError: JSON.parse: bad parsing
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse

How did you test this change?

There was a bug in packages/react-fetch/src/ReactFetchNode.js.
It's the usage of JSON.parse().

  json() {
    ...
    const json = JSON.parse(buffer.toString());
    ...
  },

JSON.parse() throws SyntaxError in the following example.

For example:

let json = JSON.parse(""); // => SyntaxError

This was discovered when testing the reactjs/server-components-demo.

I created a test code. When I ran it, it threw a SyntaxError.

  • packages/react-fetch/src/tests/ReactFetchNode-test.js
  // @gate experimental || www
  it('handles different paths with json', async () => {
    serverImpl = (req, res) => {
      switch (req.url) {
        case '/banana':
          res.write('banana');
          break;
        case '/mango':
          res.write('mango');
          break;
        case '/orange':
          res.write('orange');
          break;
      }
      res.end();
    };
    const outputs = await waitForSuspense(() => {
      return [
        fetch(serverEndpoint + 'banana').json(),
        fetch(serverEndpoint + 'mango').json(),
        fetch(serverEndpoint + 'orange').json(),
      ];
    });
    expect(outputs).toMatchObject(['banana', 'mango', 'orange']);
  });

I used the test code handles different paths as a reference.
The URL for fetch is the concatenation of the serverEndpoint of the test code and the random string banana.

http://localhost:64944/banana

Since it is not an Invalid URL, the status of the response will be as follows.

console.log(statusCode >= 200); // => true
console.log(record.status === Resolved); // => true

However, the response will not be in json format, because I have specified a random string banana.
The body of the response will be a string in which the following conditions are true.

console.log(buffer.toString().length === 0); // => true
console.log(buffer.toString() === ""); // => true

Command to run the test code:

yarn test --watch packages/react-fetch/src/__tests__/ReactFetchNode-test.js

Results:

 FAIL  packages/react-fetch/src/__tests__/ReactFetchNode-test.js
  ReactFetchNode
    ✓ can fetch text from a server component (137 ms)
    ✓ can fetch json from a server component (65 ms)
    ✓ provides response status (44 ms)
    ✓ handles different paths (29 ms)
    ✓ can produce an error (12 ms)
    ✕ handles different paths with json (16 ms)

  ● ReactFetchNode › handles different paths with json

    SyntaxError: Unexpected end of JSON input
        at JSON.parse (<anonymous>)

      155 |     }
      156 |     const buffer = readRecordValue(this._bufferRecord);
    > 157 |     const json = JSON.parse(buffer.toString());
          |                     ^
      158 |     this._json = json;
      159 |     return json;
      160 |   },

      at Response.json (packages/react-fetch/src/ReactFetchNode.js:157:21)
      at packages/react-fetch/src/__tests__/ReactFetchNode-test.js:128:57
      at retry (packages/react-suspense-test-utils/src/ReactSuspenseTestUtils.js:56:22)
      at wake (packages/react-fetch/src/ReactFetchNode.js:111:7)
      at IncomingMessage.<anonymous> (packages/react-fetch/src/ReactFetchNode.js:129:7)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 5 passed, 6 total

I modified json() as follows. I added catch { }.
If an Error throws, get it with text().

  • packages/react-fetch/src/ReactFetchNode.js
  json() {
    if (this._json !== null) {
      return this._json;
    }
    const buffer = readRecordValue(this._bufferRecord);
    try {
      this._json = JSON.parse(buffer.toString());
    } catch (error) {
      return this.text();
    }
    return this._json;
  },

Passed the test.

 PASS  packages/react-fetch/src/__tests__/ReactFetchNode-test.js
  ReactFetchNode
    ✓ can fetch text from a server component (261 ms)
    ✓ can fetch json from a server component (28 ms)
    ✓ provides response status (29 ms)
    ✓ handles different paths (24 ms)
    ✓ can produce an error (13 ms)
    ✓ handles different paths with json (20 ms)

Test Suites: 1 passed, 1 total
Tests:       6 passed, 6 total

@sizebot
Copy link

sizebot commented Nov 27, 2021

Comparing: 0cc724c...8a562fc

Critical size changes

Includes critical production bundles, as well as any change greater than 2%:

Name +/- Base Current +/- gzip Base gzip Current gzip
oss-stable/react-dom/cjs/react-dom.production.min.js = 130.01 kB 130.01 kB = 41.57 kB 41.57 kB
oss-experimental/react-dom/cjs/react-dom.production.min.js = 134.77 kB 134.77 kB = 42.97 kB 42.97 kB
facebook-www/ReactDOM-prod.classic.js = 424.63 kB 424.63 kB = 78.24 kB 78.24 kB
facebook-www/ReactDOM-prod.modern.js = 413.19 kB 413.19 kB = 76.51 kB 76.51 kB
facebook-www/ReactDOMForked-prod.classic.js = 424.63 kB 424.63 kB = 78.25 kB 78.25 kB
oss-experimental/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB
oss-stable/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB

Significant size changes

Includes any change greater than 0.2%:

Expand to show
Name +/- Base Current +/- gzip Base gzip Current gzip
oss-experimental/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB
oss-stable/react-fetch/cjs/react-fetch.node.production.min.js +2.04% 2.01 kB 2.05 kB +1.64% 0.91 kB 0.93 kB
oss-experimental/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.05 kB 5.10 kB +1.13% 1.60 kB 1.62 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.05 kB 5.10 kB +1.13% 1.60 kB 1.62 kB
oss-stable/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.05 kB 5.10 kB +1.13% 1.60 kB 1.62 kB

Generated by 🚫 dangerJS against 8a562fc

Copy link

This pull request has been automatically marked as stale. If this pull request is still relevant, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize reviewing it yet. Your contribution is very much appreciated.

@github-actions github-actions bot added the Resolution: Stale Automatically closed due to inactivity label Apr 10, 2024
Copy link

Closing this pull request after a prolonged period of inactivity. If this issue is still present in the latest release, please ask for this pull request to be reopened. Thank you!

@github-actions github-actions bot closed this Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CLA Signed Resolution: Stale Automatically closed due to inactivity
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants