Home > Net >  javascript/react Syntax error when nothing in useEffect seems to be wrong
javascript/react Syntax error when nothing in useEffect seems to be wrong

Time:11-21

When I ran my react code, I get a Syntax error

App.jsx:8 Uncaught (in promise) SyntaxError: Unexpected end of input (at App.jsx:8:1)
    at App.jsx:8:1

i dont understand why this is wrong if you look at App.jsx:

import React, {useState, useEffect} from "react";

function App() {

  const [backendData, setBackendData] = useState([{}])

  useEffect( () => {
    fetch("http://localhost:8000/api", {mode: 'no-cors'})
      .then(
        res => res.json()
      )
      .then(
        data => {
          setBackendData(data)
        }
      )
  }, [])


  return (
    <div className="App">

    </div>
  );
}

export default App;

There is nothing wrong?

CodePudding user response:

Setting the {mode: 'no-cors'} won't disable CORS errors as you would expect. It tells browser something like: Block my frontend JavaScript code from seeing contents of the response body and headers under all circumstances.

And you probably don't want that. If you have issues with CORS, it can't be fixed on frontend, this is a backend issu, so backend should return more specified headers (Access-Control-Allow-Origin to be exact)

CodePudding user response:

Your error is due a CORS issue with the target server.

To fix that you must include Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: domain.com in your server code or configuration

CodePudding user response:

maybe your API don't return a json, try this

 useEffect( () => {
fetch("http://localhost:8000/api", {mode: 'no-cors'})
  .then(result => result.text())
  .then(
    data => {
      setBackendData(data)
    }
      )
  }, [])
  • Related