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 syntax error of json.parse: bad parsing #23125

Closed
wants to merge 1 commit into from

Conversation

Biki-das
Copy link
Contributor

@Biki-das Biki-das commented Jan 16, 2022

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());
    ...
  },

For example:

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

Documents
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse
This was discovered when testing the reactjs/server-components-demo.

fix: JSON.parse fails in react-fetch
fix: JSON.parse fails in react-fetch reactjs/server-components
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 Jan 16, 2022

Comparing: 3dc41d8...5afd703

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 = 129.52 kB 129.52 kB = 41.53 kB 41.53 kB
oss-experimental/react-dom/cjs/react-dom.production.min.js = 134.65 kB 134.65 kB = 43.01 kB 43.01 kB
facebook-www/ReactDOM-prod.classic.js = 427.76 kB 427.76 kB = 78.53 kB 78.53 kB
facebook-www/ReactDOM-prod.modern.js = 417.45 kB 417.45 kB = 77.06 kB 77.06 kB
facebook-www/ReactDOMForked-prod.classic.js = 427.76 kB 427.76 kB = 78.53 kB 78.53 kB
oss-experimental/react-fetch/cjs/react-fetch.node.production.min.js +2.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.production.min.js +2.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 kB
oss-stable/react-fetch/cjs/react-fetch.node.production.min.js +2.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 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.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.production.min.js +2.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 kB
oss-stable/react-fetch/cjs/react-fetch.node.production.min.js +2.05% 2.00 kB 2.04 kB +1.76% 0.91 kB 0.92 kB
oss-experimental/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.04 kB 5.09 kB +1.13% 1.59 kB 1.61 kB
oss-stable-semver/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.04 kB 5.09 kB +1.13% 1.59 kB 1.61 kB
oss-stable/react-fetch/cjs/react-fetch.node.development.js +1.05% 5.04 kB 5.09 kB +1.13% 1.59 kB 1.61 kB

Generated by 🚫 dangerJS against 5afd703

Copy link

@glsscnnn glsscnnn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice.

@Biki-das Biki-das changed the title Fix sytax error of json.parse: bad parsing Fix syntax error of json.parse: bad parsing Jan 18, 2022
@gaearon
Copy link
Collaborator

gaearon commented Apr 13, 2022

If the response is not actually valid JSON, it should throw. We should not silently convert it to string.

@gaearon gaearon closed this Apr 13, 2022
@Biki-das
Copy link
Contributor Author

If the response is not actually valid JSON, it should throw. We should not silently convert it to string.

Oh got that!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants