Reputation: 1217
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>
);
}
}
Upvotes: 63
Views: 134000
Reputation: 1
None of the above answers worked for me when I was getting the same issue. This issue might totally depend on your project and the mistakes you're making. For me I was using class component and I was binding a method and later I commented the same method. So the binding line was throwing the same error for me. Application worked after commenting the binding line later.
Upvotes: 0
Reputation: 3943
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>
Upvotes: 0
Reputation: 1
I had this error one time, and my problem was that I didn't define a let
/const
for one of my variables.
Upvotes: 0
Reputation: 8162
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.
Upvotes: 31
Reputation: 9
Findout if you are parse javascript object using JSON.parse()..It may cause this type of error in react.js!
Upvotes: 0
Reputation: 2256
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") || '{}');
<==============
Upvotes: 1
Reputation: 900
check your local storage. I think an undefined value is there That's why this error occurred
Upvotes: 5
Reputation: 1698
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
Upvotes: 0
Reputation: 1322
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.
Upvotes: 1
Reputation: 2322
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
Upvotes: 2
Reputation: 431
If possible do not user any where in the render or state : JSON.parse("your data"), I have solved that issue removing in mycomponent
Upvotes: 1
Reputation: 1850
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.
Upvotes: 0
Reputation: 1027
It sometimes caused by the browser.
I have closed my browser and opened it. It solved my issue.
Upvotes: 0
Reputation: 303
I got this error too. Clearing the localStorage makes the error go away.
Upvotes: 9
Reputation: 17382
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
Upvotes: 5
Reputation: 51
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
Upvotes: 3
Reputation: 451
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.
Upvotes: 0
Reputation: 594
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! :)
Upvotes: 1
Reputation: 104
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.
Upvotes: -1
Reputation: 900
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
Upvotes: 4
Reputation: 667
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
Upvotes: 65
Reputation: 1
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
Upvotes: 0
Reputation: 706
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())
})
}
Upvotes: 4
Reputation: 487
This is not a CORS problem. Generally, there is an issue in calling the function. check this line
this.props.onCreate(this.state.zone)
Upvotes: 9