Help requested from React/MSW users!

I’m trying to integrate MSW into my Vite/React App and I’m not getting back the responses that I’m expecting.

The useEffect is the most relevant part for now…,


  useEffect(() => {
    const getData = async () => {
      const response = await fetch("/sessions")
      return await response.json().then(
        res => console.log(res)
    const data = getData();
  }, [])

At the moment, it looks like the server is intercepting the response and I’m getting the correct response from MSW here!

However the moment I want to actually do anything with this data I get the following error.

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON

When I check the text of an await like this

  useEffect(() => {
    const getData = async () => {
      const response = await fetch("/sessions")
      const data = await response.text()
  }, [])
<!doctype html>
<html lang="en">
    <script type="module">
import RefreshRuntime from "/@react-refresh"
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>

There is definitely something wrong and I’d be grateful for help in trouble shooting here!

The MSW part is afaics not relevant here: if you are using that for testing, then what you are doing is providing a mock value so that you can actually test some code that won’t work unless the server response is there.

The error is because the response is HTML. Therefore when you run the .json() method it all blows up because it’s impossible to parse as JSON

Log the response and see what it is: at the minute you’re logging after you try to parse.

Hi there, it turned out there was an issue to do with importing in es6.

I found a solution, thanks for your help. I thought the spirit of the FCC forum was about helping each other out which was why I posted for help.

Appreciate your suggestion Dan.

1 Like

Try to put “https://” head of your URL.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.