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

Javascriptnode.jsReactjsSuperagent

Javascript Problem Overview


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>
    );
  }
}

Javascript Solutions


Solution 1 - Javascript

Frequently I too get this error, to solve this error **1. Open Dev tools

  1. Go to Application section
  2. Clear the local storage by right clicking it.**

Hope your error is resolved

Solution 2 - Javascript

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.

Solution 3 - Javascript

for me, I just cleared site data and working fine

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

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

Solution 6 - Javascript

Clearing a token storage worked for me.

Solution 7 - Javascript

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

Solution 8 - Javascript

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())
        })
}

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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! :)

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

It sometimes caused by the browser.

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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.

Solution 17 - Javascript

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") || '{}'); <==============

Solution 18 - Javascript

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

Solution 19 - Javascript

Clearing token in local storage helped me.

Solution 20 - Javascript

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.

Solution 21 - Javascript

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.

Solution 22 - Javascript

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.

Solution 23 - Javascript

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

Solution 24 - Javascript

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

Solution 25 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliamView Question on Stackoverflow
Solution 1 - JavascriptSAIFUL ISLAMView Answer on Stackoverflow
Solution 2 - JavascriptjfunkView Answer on Stackoverflow
Solution 3 - JavascriptzulqarnainView Answer on Stackoverflow
Solution 4 - JavascriptAbdulsalamView Answer on Stackoverflow
Solution 5 - JavascriptAnuruddha ThennakoonView Answer on Stackoverflow
Solution 6 - JavascriptDipesh LohaniView Answer on Stackoverflow
Solution 7 - JavascriptSpandan JoshiView Answer on Stackoverflow
Solution 8 - JavascriptRyan BrockhoffView Answer on Stackoverflow
Solution 9 - JavascriptSpandan JoshiView Answer on Stackoverflow
Solution 10 - JavascriptmowwwalkerView Answer on Stackoverflow
Solution 11 - JavascriptSiddhant VarmaView Answer on Stackoverflow
Solution 12 - JavascriptZurc SoirrabView Answer on Stackoverflow
Solution 13 - JavascriptJimView Answer on Stackoverflow
Solution 14 - JavascriptDineshView Answer on Stackoverflow
Solution 15 - JavascriptManu PanduuView Answer on Stackoverflow
Solution 16 - JavascriptSjors HijgenaarView Answer on Stackoverflow
Solution 17 - JavascriptWahab ShahView Answer on Stackoverflow
Solution 18 - JavascriptVinod ChauhanView Answer on Stackoverflow
Solution 19 - JavascriptDeepaView Answer on Stackoverflow
Solution 20 - JavascriptKamran HyderView Answer on Stackoverflow
Solution 21 - JavascriptSummmerFortView Answer on Stackoverflow
Solution 22 - JavascriptLuis FebroView Answer on Stackoverflow
Solution 23 - JavascriptNafazBenzemaView Answer on Stackoverflow
Solution 24 - JavascriptRipu Daman SharmaView Answer on Stackoverflow
Solution 25 - JavascriptSteveView Answer on Stackoverflow