question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Uncaught (in promise) SyntaxError: Unexpected end of input

See original GitHub issue

Describe the bug

After updating the msw package from 0.15.5 to 0.19.0 and update the mockServiceWorker.js file, the service worker started throwing the following error

Uncaught (in promise) SyntaxError: Unexpected end of input at line 111

After some debugging I was able to fix the issue ( at least for me ) by replacing

 const body = request.headers.get('content-type')?.includes('json')
        ? await request.json()
        : await request.text()

with

const isJSONContentType = request.headers.get('content-type')?.includes('json')
let body;
if (isJSONContentType) {
  try {
    body = await request.json()
  } catch (error) {
    console.warn(error)
    body = await request.text()
    console.log({body,headers: Object.fromEntries(request.headers.entries()), url: request.url})
  }
} else  {
  body = await request.text()
}

with this fix I’m getting the correct mocked responses but what I don’t understand is why the body is showing up empty

Environment

  • msw: 0.19.0
  • nodejs: 12.13.1
  • npm: 6.14.5
  • webpack: 4.42.1
  • webpack-dev-server: 3.10.3

The requests that are failing match with a Webpack DevServer proxy that I have in my environment. The proxy takes every request url starting with "/api" to a live server

Webpack devServer config:

devServer: {
    contentBase: "./public",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
    },
    host: !process.argv.join(" ").includes("--sw") && require("ip").address(),
    disableHostCheck: true,
    open: true,
    hot: false,
    port,
    proxy: {
      "/api": {
        target: "https://live.server.domain.cloud",
        secure: false,
        changeOrigin: true,
        withCredentials: true,
      }
    }
  },

Please also provide your browser version.

Chrome 83.0.4103.61

To Reproduce

Steps to reproduce the behaviour:

  1. Run the webapp with msw enabled
  2. in the console you’ll see the error Uncaught (in promise) SyntaxError: Unexpected end of input
  3. if you refresh the browser you’ll find that the request for the webpack index.html file is hanging and will not resolve

Expected behavior

Shouldn’t throw if the suspected response has the Content-Type header containing "json" and the body is empty

Screenshots

Original error

image

chrome console after I added some logs and error handling on mockServiceWorker.js

image

Network tab of the same session / request after the fix showing expected mocked data

image

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:7 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
vlad-khitev-axoncommented, Jun 7, 2020

Having the same issue. I suppose it’s because of the dev proxy server. I use create-react-app and this is my setupProxy.js file:

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
    ['/auth', '/api'],
    createProxyMiddleware({
      target: process.env.DEV_PROXY,
      changeOrigin: true,
    }),
  )
}

This is how I make a request:

window.fetch(url, {
  headers: {
    'Content-Type': 'application/json',
  },
})

Before the setupProxy.js file was created, msw worked fine.

2reactions
kettanaitocommented, Jun 6, 2020

Additionally, in the current implementation of the client-side parsing of the worker message, we already check for empty strings, and prevent parsing as JSON in that case:

https://github.com/mswjs/msw/blob/5defbf2b4f4d7ae1503cb68a4e7be14e994b3f7d/src/utils/parseRequestBody.ts#L4-L18

I really think we should do only this when handling request body in the worker:

const reqBody = await request.text()

I’d expect that to handle even the binary files, converting blobs to text, and then letting the client-side library parsing to decide how to parse that.

@mouhannad-sh, please, would you be interested in helping me with this fix? I’d gladly assist in code reviews and share any necessary insights about the library.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Uncaught (in promise) SyntaxError: Unexpected end of JSON ...
I am trying to send a new push subscription to my server but am encountering an error "Uncaught (in promise) SyntaxError: Unexpected end...
Read more >
[React] Uncaught (in promise) SyntaxError: Unexpected end of ...
When i make a program using react, i saw this matter. I confirmed my code(input JSON body), but there was no issue. 2....
Read more >
Uncaught SyntaxError: Unexpected end of JSON ... - STechies
A common error encountered by JavaScript programmers is the Uncaught SyntaxError: Unexpected end of JSON input. This is usually observed when the coder...
Read more >
Uncaught (in promise) SyntaxError: Unexpected end of JSON ...
The code does not run - the problem that pops in the console is -. Uncaught (in promise) SyntaxError: Unexpected end of JSON...
Read more >
Unexpected end of input Error in JavaScript | bobbyhadz
The "Uncaught SyntaxError Unexpected end of input" error occurs for 3 main reasons: · You can paste your code into an online Syntax...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found