62

Every time I submit a zone, it displays this error:

'Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development'

It only occurs when I press on the submit zone button which I guess is happening when the old states are being changed to the new one. (this.setState)

CreateZone.js

import React, { Component } from "react";

export default class CreateZone extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zone: {
        name: "",
        zipCode: "",
      },
    };
  }

  updateZone(event) {
    let updated = Object.assign({}, this.state.zone);
    updated[event.target.id] = event.target.value;
    this.setState({
      zone: updated,
    });
  }

  submitZone(event) {
    console.log("SubmitZone: " + JSON.stringify(this.state.zone));
    this.props.onCreate(this.state.zone);
  }

  render() {
    return (
      <div>
        <input
          onChange={this.updateZone.bind(this)}
          className="form-control"
          id="name"
          type="text"
          placeholder="Name"
        />{" "}
        <br />
        <input
          onChange={this.updateZone.bind(this)}
          className="form-control"
          id="zipCode"
          type="text"
          placeholder="Zip Code"
        />{" "}
        <br />
        <input
          onClick={this.submitZone.bind(this)}
          className="btn btn-danger"
          type="submit"
          value="Submit Zone"
        />
      </div>
    );
  }
}

Zones.js

import React, { Component } from "react";
import superagent from "superagent";
import { CreateZone, Zone } from "../presentation";

export default class Zones extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
    };
  }

  componentDidMount() {
    console.log("componentDidMount");
    superagent
      .get("/api/zone")
      .query(null)
      .set("Accept", "application/json")
      .end((err, response) => {
        if (err) {
          alert("ERROR: " + err);
          return;
        }
        console.log(JSON.stringify(response.body));
        let results = response.body.results;
        this.setState({
          list: results,
        });
      });
  }

  addZone(zone) {
    let updatedZone = Object.assign({}, zone);
    updatedZone["zipCodes"] = updatedZone.zipCode.split(",");
    console.log("ADD ZONE: " + JSON.stringify(updatedZone));

    superagent
      .post("/api/zone")
      .send(updatedZone)
      .set("Accept", "application/json")
      .end((err, response) => {
        if (err) {
          alert("ERROR: " + err.message);
          return;
        }
        console.log("ZONE CREATED: " + JSON.stringify(response));
        let updatedList = Object.assign([], this.state.list);
        updatedList.push(response.result);
        this.setState({
          list: updatedList,
        });
      });
  }

  render() {
    const listItems = this.state.list.map((zone, i) => {
      return (
        <li key={i}>
          {" "}
          <Zone currentZone={zone} />{" "}
        </li>
      );
    });

    return (
      <div>
        <ol>{listItems}</ol>
        <CreateZone onCreate={this.addZone.bind(this)} />
      </div>
    );
  }
}

Zone.js

import React, { Component } from "react";

import styles from "./styles";

export default class Zone extends Component {
  render() {
    const zoneStyle = styles.zone;

    return (
      <div style={zoneStyle.container}>
        <h2 style={zoneStyle.header}>
          <a style={zoneStyle.title} href="#">
            {" "}
            {this.props.currentZone.name}{" "}
          </a>
        </h2>
        <span className="detail"> {this.props.currentZone.zipCodes} </span>{" "}
        <br />
        <span className="detail">
          {" "}
          {this.props.currentZone.numComments} comments{" "}
        </span>
      </div>
    );
  }
}
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
William
  • 1,107
  • 2
  • 11
  • 18
  • Your error has nothing to do with react. Read more on CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – cdoshi Feb 04 '18 at 19:31

26 Answers26

65

Frequently I too get this error, to solve this error 1. Open Dev tools 2. Go to Application section 3. Clear the local storage by right clicking it.

Hope your error is resolved

SAIFUL ISLAM
  • 667
  • 5
  • 2
  • 2
    why what is it that is breaking..... hope it doesn't happen in prod env – Akki619 Mar 04 '21 at 18:16
  • 1
    but when I refresh the page, error still occurs. any possible solution for that? – Chandler Bing Aug 18 '21 at 04:55
  • If this doesn't fix your problem, you should also try the suggestions at https://reactjs.org/docs/cross-origin-errors.html – Alex von Brandenfels Aug 23 '21 at 19:23
  • if you get this error "frequently" maybe clearing local cookies is not the solution ;) – Sonic Soul Sep 21 '21 at 16:08
  • For you the error may be happening in the local storage object, but it could just as well happen in a cookie or other data. This is not a solution unless the problem you're running into is happening in the local storage (not writing data to local storage correctly). – John Mar 04 '22 at 20:33
32

I was getting this error while I was using JSON.parse() on the value of a cookie I had set.

(Edit: seems to be only in Chrome, FF throws parsing error, see comments)

React throws a cross-origin error whenever JSON.parse() receives an invalid string. Check the validity of the JSON value you are storing, since JSON structures are strict about their format.

jfunk
  • 7,176
  • 4
  • 37
  • 38
  • Where's your answer? Did you fix it? – Sjors Hijgenaar Aug 19 '21 at 07:03
  • 1
    I've added some more information to the answer, I hope it helps. – jfunk Aug 19 '21 at 14:23
  • Good answer, this was the problem for me as well, I tried to `JSON.parse()` an empty URL parameter - the argument of the parse was therefore "undefined" and react did throw the error, which as @jfunk correctly notes is interpreted as a cross-origin error. – Sváťa Filev Oct 07 '21 at 09:04
  • I was getting the same issue, and this was the reason for my error being thrown! – Tekill Dec 20 '21 at 18:50
  • 1
    I had the same issue, but I realized about the parsing error when I used Firefox instead of Chrome, since the former indicated there was a parsing error instead of the cross-origin issued by Chrome. – drasc Jan 27 '22 at 14:27
26

for me, I just cleared site data and working fine

zulqarnain
  • 1,536
  • 4
  • 26
  • 44
9

I got this error too. Clearing the localStorage makes the error go away.

  1. Open your console in the developer tool.
  2. Locate the application tab.
  3. Locate the local storage.
  4. Right click on the locale storage and click on clear to clear the console.
Abdulsalam
  • 275
  • 4
  • 6
8

This is not a CORS problem. Generally, there is an issue in calling the function. check this line

this.props.onCreate(this.state.zone)
6

Clearing a token storage worked for me.

Dipesh Lohani
  • 306
  • 3
  • 11
5

check your local storage. I think an undefined value is there That's why this error occurred

Spandan Joshi
  • 809
  • 10
  • 11
5

Literally the first thing mentioned on https://reactjs.org/docs/cross-origin-errors.html, but in case anyone else came here first:

<script crossorigin src="..."></script>

Needed if you're serving your bundles from a different domain than your page. Eg. I was hitting localhost:8040 in the browser and serving the bundles from the webpack dev server at localhost:3000

mowwwalker
  • 16,634
  • 25
  • 104
  • 157
4

If it helps anyone, I had a similar issue trying to call a callback function with part of my state as the argument. My resolution was calling it after a promise for Component Did Mount. Might help someone, even though this isn't an exact solution for your code:

componentDidMount() {
    const { clientId } = this.props
    axios.get(`/api/getpayments/${clientId}`)
        .then(response => {
            this.setState({ payments: response.data })
        })
        .then(() => {
            this.props.updateProgressBar(this.state.payments.slice())
        })
}
Ryan Brockhoff
  • 617
  • 1
  • 7
  • 8
4

Check your token object. that's maybe undefined in local storage. you need to clear that and everything will be fine. clear your local storage or cookie where you store your token

Spandan Joshi
  • 809
  • 10
  • 11
2

You may be are getting this error for this line:

console.log('SubmitZone: ' + JSON.stringify(this.state.zone))

You are trying to cast this.state.zone into a string typed value when may be, it is null, empty or it's not well formatted

2

Those saying "clear your localStorage"...what if i need localStorage...?

The better approach would be to review each point you're accessing your localStorage. Check each input and output point. confirm your input and output is what your expecting, meaning not only IS there output, but what type is it?

For example, if you have a token and you're trying to JSON.parse(yourToken) and your token isn't a string, or hasn't been stringified...you will get this error

Jim
  • 1,988
  • 6
  • 34
  • 68
  • 1
    This needs to go higher, I think one answer on clearing localStorage should suffice. Jim's answer helped me solve my problem. Looked for JSON.parse in my subsequent code and found a faulty JSON datestring to be the culprit. – Sjors Hijgenaar Aug 19 '21 at 07:19
1

I was getting the same error again and again because my context store was trying to access something from the localStorage which was undefined. In case anyone stumbled upon this error using the context API, clearing localStorage might help as said in many answers above! :)

Siddhant Varma
  • 574
  • 5
  • 10
  • 1
    Please point out what new aspect of the question your answer addresses so that it isn't mistaken as just repeating things that are already covered in existing answers. – Jason Aller Aug 12 '20 at 19:22
1

If possible do not user any where in the render or state : JSON.parse("your data"), I have solved that issue removing in mycomponent

Manu Panduu
  • 411
  • 1
  • 9
  • 17
1

For me this error is thrown when I call setState from inside a callback function. While the error is thrown on the setState the actual error came from what comes next: rendering the DOM (initiated by setState).

componentDidMount() {  
    if (this.state.songs.length === 0) 
        fetch("/collection/tracks")
        .then(res => res.json())
        .then(data => {
            this.setState({
                songs: data
            });
        });
}

From rendering I then tried to parse a JSON date that is the reall cullprit, as it was trying to do so on apparently not a JSON datestring:

{new Date(JSON.parse(song.added_at)).toLocaleDateString()}

Like @Jim's answer: look at the code that comes after as well.

Sjors Hijgenaar
  • 1,232
  • 1
  • 16
  • 30
1

I was getting the error because of JSON.parse(localStorage.getItem("user") || ''); The issue is if JSON.parse() doesn't get proper format it was throwing this error.

The only change I did was pass empty object in single quotes like this '{}'

LIKE THIS BELOW

JSON.parse(localStorage.getItem("user") || '{}'); <==============

Wahab Shah
  • 2,066
  • 1
  • 14
  • 19
0

I also got the same issue on sandbox while doing code with react-redux. Whenever you directly call this.props.anymethod() it will revert you with this error. Try to handle it locally and then from within method hit the props method.

Something like this:

I solved cross-origin problem in this scenario

AS Mackay
  • 2,831
  • 9
  • 19
  • 25
0

This is shown because React does not show the traceback of the error due to security concerns. The error could be unrelated to CORS altogether. I suggest to look at the console for errors that would show up. Resolving those errors may solve your issue.

SummmerFort
  • 369
  • 3
  • 8
0

It sometimes caused by the browser.

I have closed my browser and opened it. It solved my issue.

Dinesh
  • 812
  • 4
  • 14
0

Surprisingly my issue was in the local storage due to a misplaced comma.

If you put a comma like this: { "myVar":true, } and reload your dev environment, then this error will be thrown. All it took to go back to normal was take it away.

I am documenting this as an answer so that I can recall it when I am doing some local storage testing and maybe help someone out there with the same issue since the solution proposed by React`s page suggest a different approach.

The takeaway is be aware when you are dealing with local storage.

Luis Febro
  • 1,733
  • 1
  • 16
  • 21
0

This error often occurs when you have some data in object format on local storage and trying to convert the object to object in development using JSON.parse() method.

localStorage.setItem("user",user); //store as object

const user = JSON.parse(localStorage.getItem("user")); // trying to convert to object
Nafaz M N M
  • 1,558
  • 2
  • 27
  • 41
0

Findout if you are parse javascript object using JSON.parse()..It may cause this type of error in react.js!

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '21 at 09:21
  • This was already mentioned in the other answers on this same question [3 months ago](https://stackoverflow.com/questions/48611310/uncaught-error-a-cross-origin-error-was-thrown-react-doesnt-have-access-to-th/69790093#69790093), [4 months ago](https://stackoverflow.com/questions/48611310/uncaught-error-a-cross-origin-error-was-thrown-react-doesnt-have-access-to-th/69322878#69322878) and [11 months ago](https://stackoverflow.com/questions/48611310/uncaught-error-a-cross-origin-error-was-thrown-react-doesnt-have-access-to-th/66122439#66122439) – aerial Jan 02 '22 at 06:29
0

I had this error one time, and my problem was that I didn't define a let/const for one of my variables.

Steve
  • 1
0

It is clearly described what the issue is in the old (legacy) docs of React.

https://legacy.reactjs.org/docs/cross-origin-errors.html

I had the situation, that in development mode, I was running the source codes on port 3002, while the rest of the page was running on port 7777. So the message "A cross-origin error was thrown. React doesn't have access to the actual error object in development" makes perfect sense.

I was able to solve this issue (as described in the docs) by adding "crossorigin" property in the link to the JS file.

<script crossorigin type="text/javascript" src="http://localhost:3002/static/js/bundle.js"></script>
dns_nx
  • 3,651
  • 4
  • 37
  • 66
-1

Clearing token in local storage helped me.

Deepa
  • 1
-1

Closing the application window in other browser instances could help with this error. Specifically the error is related to the browser behavior described here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.