Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to get rid of cross-origin error? #667

Closed
mescalito opened this issue Mar 26, 2018 · 66 comments
Closed

how to get rid of cross-origin error? #667

mescalito opened this issue Mar 26, 2018 · 66 comments
Labels

Comments

@mescalito
Copy link

mescalito commented Mar 26, 2018

IN FIREFOX: When I execute my code the typical error I should get is: "TypeError: Cannot read property 'setState' of undefined", instead I received a very weird cross-origin error.

Here is a screenshot of the error:
http://prntscr.com/iwipnb
image

Error
A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://fb.me/react-crossorigin-error for more information.

here is my code: https://codesandbox.io/s/4885l37xrw

How can I avoid the cross-origin error in Codesandbox?

@mescalito
Copy link
Author

mescalito commented Mar 26, 2018

It looks like you need to enable CORS on your S3 bucket that serves: https://s3-eu-west-1.amazonaws.com/codesandbox-downtime/downtime.json

To do so, just navigate to your bucket, then click the Permissions tab, then in the CORS box enter an XML document with the permissions you'd like. Sample permissions to allow any host to make a GET request:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://*</AllowedOrigin>
    <AllowedOrigin>https://*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>

Thanks to: duhaime
https://stackoverflow.com/questions/49493279/react-js-how-to-get-rid-of-cross-origin-error-in-codesandbox

@CompuIves
Copy link
Member

This is a serious issue, we need to fix this quick. The reason for these cross origin errors is that we use eval to evaluate the code in the browser (https://reactjs.org/docs/cross-origin-errors.html#source-maps). The solution is to put the code in script tags, and we can definitely do that, but it's a big change to our bundler.

I will take a look at it this weekend, and check if performance is affected if we put all code in script tags. Thanks for opening this issue!

@SirBryan
Copy link

SirBryan commented May 9, 2018

I'm seeing the same issue with a simple Node service running on Now (Zeit). I can send POST's to the service, but GET's and any data returned on POST's is ignored (fetch is showing CORS errors and XHTTP puts up a response status of 0 instead of 200).

(Code at https://codesandbox.io/s/1oyy6mp0vq and https://zeit.co/sirbryan/simplenode/uhnsgppoho/source?f=index.js )

@lbogdan
Copy link
Contributor

lbogdan commented May 10, 2018

@SirBryan You need to return CORS headers from your Node service, in order to be able to access it from external sites (like your codesandbox.io sandbox).

@SirBryan
Copy link

Thanks for that reminder. It had been a while since I had to mess with headers on the server end...

@boscorona
Copy link

@CompuIves I'm having a similar issue when trying to make a API call to https://deckofcardsapi.com/api/deck/new/

problem

How can I resolve this?

@CompuIves
Copy link
Member

Hmm, I think that decks of card API should return CORS headers to make it work from cross origins in this case. Or you could set up your own proxy that adds the headers locally with something like express-proxy, but that's quite hacky.

@boscorona
Copy link

Yes looks like the API isn't returning CORS headers, I'll have to develop locally. Thanks for the help @CompuIves.

@meetzaveri
Copy link

meetzaveri commented Jan 4, 2019

@CompuIves @mescalito @lbogdan I had same issue.

Then I came to know that the custom method I used, I didn't binded like this.customMethod = this.customMethod.bind(this); or used arrow function syntax instead.

So it's like we have to use either arrow functions by adding babel preset or we have to bind it.

It's now working 🙌

@AndyOGo
Copy link

AndyOGo commented Mar 20, 2019

I have the error if I create <custom-elements> wrap them with @skatejs/val to render them with react 😲
https://codesandbox.io/s/l4jkw43q7

As soon as I remove all wrapper custom elements, all CORS errors are gone.
I have no special API or whatever calls 🤔
Only the hyperscript (h) function os React.createElement is wrapped and I have an inline /** @jsx h */ comment.

EDIT:
Meanwhile I found the bug, @skatejs/val seems not to support implicit children passed by spreaded {...this.props}, instead I had to explicitly use JSX-style children.

@lbogdan
Copy link
Contributor

lbogdan commented Mar 21, 2019

Hopefully this was solved, and we forgot to close it.

@lbogdan lbogdan closed this as completed Mar 21, 2019
@AndyOGo
Copy link

AndyOGo commented Mar 21, 2019

@lbogdan
I hope so too, but I experienced the bug yesterday 🤔

@lbogdan
Copy link
Contributor

lbogdan commented Mar 21, 2019

Looks like I got lost in the unrelated comments, and missed the actual issue 🙂 , reopening.

@lbogdan lbogdan reopened this Mar 21, 2019
@CompuIves
Copy link
Member

Yes! Still valid bug, the problem is that we execute code using eval, and that causes React to have this cross origin issue. I can make an exception and include the UMD build of React as a script tag to circumvent the issue. It's really ugly and manual, but would at least solve this.

Another way might be to evaluate everything using script tags, but this is quite tricky since every file would require its own script tag.

@AndyOGo
Copy link

AndyOGo commented Mar 21, 2019

I don't know the current implementation.

But from what you say, I'm convinced that one script tag for each file is the best option.

Correct me, if I'm wrong. I would object that this isn't tricky at all.
If you do know all scripts, iterate over all files and eval their content?
You would just replace eval by document.createElement('script'); ... and append it to the DOM.
Maybe you have to occasionally remove/replace those script tags if they get outdated or removed, etc 🤔

@iamricky
Copy link

iamricky commented Apr 3, 2019

Has this bug been addressed? or is the solution switching to codepen?

@CompuIves
Copy link
Member

Correct me, if I'm wrong. I would object that this isn't tricky at all.

That's right! Implementation wise I think that it's not a lot of changes, I'm a bit afraid for sandboxes with >1000 files. Creating 1000 script tags for a sandbox might be expensive, but then again, I haven't tested it yet. We're on a bug fixing spree this week so I think we'll address this this week!

@SaraVieira
Copy link
Contributor

Has this bug been addressed? or is the solution switching to codepen?

No and yes

@AndyOGo
Copy link

AndyOGo commented Apr 3, 2019

I see, that could be maaaany files 🤔
I haven't tested so many files either, but would it be possible to concatenate them or run a full fledged build?

How about the Function constructor? Does it have the same cross origin issue?

Seems not, as the react docs says:

Some JavaScript bundlers may wrap the application code with eval statements in development. (For example Webpack will do this if devtool is set to any value containing the word “eval”.) This may cause errors to be treated as cross-origin.
https://reactjs.org/docs/cross-origin-errors.html#source-maps

@shrutikapoor08
Copy link

I am still experiencing this issue. Here is a sandbox link I am working on: https://codesandbox.io/s/n4xno16npj. Not sure if this is GraphCMS setting or codesandbox issue.

@AndyOGo AndyOGo mentioned this issue Apr 3, 2019
4 tasks
@AndyOGo
Copy link

AndyOGo commented Apr 3, 2019

@CompuIves I started to provide above PR, from a first quick github search I hope haven't missed something.

@AndyOGo
Copy link

AndyOGo commented Apr 14, 2019

May it helps to enable CORS as suggested here:
https://stackoverflow.com/questions/48953727/display-cross-origin-react-error-boundary-errors-with-webpack-devtool-eval

And here is an extensive issue discussion:
facebook/react#10441

@AndyOGo
Copy link

AndyOGo commented Apr 14, 2019

Also setting 'unsafe-eval' For CSP header could help🤔
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

@robertkofoed
Copy link

If anyone is looking for a temporary work-around to be able to inspect the error object closer (without being blocked by "A cross-origin error was thrown"...). You could create a new Chrome shortcut and append some flags to make it unsafe (no more CORS):
Add

--disable-web-security --user-data-dir="C:/ChromeDevSession"

to the launch target.

Source: https://stackoverflow.com/a/45433997/6286479

@madrus
Copy link

madrus commented Nov 13, 2019

I ran into this issue as well with React 16.11.0.

Same here with useHistory hook. Try uncommenting the useHistory lines in src/App.tsx file of my otherwise working sandbox. This happens in Chrome. If I open it with Edge, the error is slightly different: TypeError: Unable to get property 'history' of undefined or null reference

@alexdevero
Copy link

I ran into this issue as well with React 16.11.0.

Same here with useHistory hook. Try uncommenting the useHistory lines in src/App.tsx file of my otherwise working sandbox. This happens in Chrome. If I open it with Edge, the error is slightly different: TypeError: Unable to get property 'history' of undefined or null reference

Good observation.

This error may not be specifically about cross-origin problem. In my app, I solved this error by adding some default, empty, values for the data I wanted to fetch from API. After this, the error disappeared and app worked.

So, the real error can actually be caused by some null or undefined, not cross-origin error per se.

Any thoughts about this @CompuIves?

@santosh898
Copy link

Allowed CORS using https://addons.mozilla.org/en-US/firefox/addon/access-control-allow-origin/

Expected this issue to be gone. but that did'nt happen. may be there is another reason. or am i missing something here?

@dejay-at-work
Copy link

Still having this issue, and it's hindering our company's ability to use this as a tool for remote interviews. Obviously, we cannot ask our hiring candidates to fiddle around with their browsers to overcome these issues.

@chintanvyas360
Copy link

can't debug serverless code due to this issue. It's working fine elsewhere. I'm stuck with the same issue in vscode debug.

@AndyOGo AndyOGo mentioned this issue Nov 29, 2019
4 tasks
@AndyOGo
Copy link

AndyOGo commented Nov 29, 2019

@jdolearydl
Copy link

jdolearydl commented Dec 3, 2019

This happened to me when I accidentally invoked setState within a React Functional Component.
https://codesandbox.io/s/react-88o0s
Without eslint to identify the problem, this is hard to track down.

@AndyOGo
Copy link

AndyOGo commented Dec 3, 2019

@jdolearydl

I also created a reproduction for your case at my PR #3098

@alundiak
Copy link

alundiak commented Dec 6, 2019

@AndyOGo I hope after, that after merging those PRs issue will be gone? Is it really codesandbox issue? I also have same error w React/ReactDOM, Redux and Express and connected-react-router, but I'm not yet sure if it's the fact of my code or codebox behavior?

Here is url to original codebox I found recently - https://codesandbox.io/s/ymk0787ox
I wanted to fix it, forked, - I tried to downgrade to React DOM 16.8.6 but then I faced with my forked version can't run now anyhow (browser stuck).

@jeffryang24
Copy link

Sometime the cross origin error occurs if you forget to import react when using JSX. (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md). For example, inside codesandbox

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './app';

import './styles.css';

function Main() {
  return <App />;
}

const rootElement = document.getElementById('root');
ReactDOM.render(<Main />, rootElement);

app.js

// This gonna cause error in codesandbox (currently).
function App() {
  return <p>asdasd</p>;
}

export default App;

app.js

// This should solve the error.
import React from 'react';

function App() {
  return <p>asdasd</p>;
}

export default App;

Yes, the cross origin is confusing since we don't know what actually the error is... 🙇‍♂️

@jeffryang24
Copy link

jeffryang24 commented Dec 10, 2019

Current temporary solution to let you know the actual error is by using error boundary and then open the project in the new window. You will find the clue for your error inside the browser console in your new browser window. (The error doesn't appear inside codesandbox console... 🤔 don't know why...)

ErrorBoundary.js (copy paste from react official doc here)

import React, { Component } from 'react';

class ErrorBoundary extends Component {
  state = {
    hasError: false
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(`Error: `, error);
    console.log(`Error info: `, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <p>Oops.... Error just invaded this page...</p>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Then, wrap you App children with error boundary, such us

<ErrorBoundary>
  <FormProvider>
    <MyApp />
  </FormProvider>
</ErrorBoundary>

Finally, open your project in new window. React will give a little clue about your error... 🙇‍♂️

error_from_above_thread

Above error is an example for my previous thread...

@jeffryang24
Copy link

Current temporary solution to let you know the actual error is by using error boundary and then open the project in the new window. You will find the clue for your error inside the browser console in your new browser window. (The error doesn't appear inside codesandbox console... don't know why...)

ErrorBoundary.js (copy paste from react official doc here)

import React, { Component } from 'react';

class ErrorBoundary extends Component {
  state = {
    hasError: false
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.log(`Error: `, error);
    console.log(`Error info: `, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <p>Oops.... Error just invaded this page...</p>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Then, wrap you App children with error boundary, such us

<ErrorBoundary>
  <FormProvider>
    <MyApp />
  </FormProvider>
</ErrorBoundary>

Finally, open your project in new window. React will give a little clue about your error...

error_from_above_thread

Above error is an example for my previous thread...

Sorry, actually you don't need error boundary. Just open your project in the new window, and you will find the error clue inside the browser console. 🙇‍♂️

@natkuhn
Copy link

natkuhn commented Dec 12, 2019

In case it is helpful, here is a Minimal non-Working Example (MnWE) of the CORS error. Maybe a dozen lines in all. The only external resources are completely standard (Material-UI).

This is the second project in a row where this has happened, so I am guessing it happens to a lot of folks.

https://codesandbox.io/s/cors-error-demo-uvsoo

@natkuhn
Copy link

natkuhn commented Dec 12, 2019

In case it is of any help, here is a minimal example of the problem, less than a dozen lines of code, using just React and Material-UI.

https://codesandbox.io/s/cors-error-demo-uvsoo

The error is caused by an undefined variable in the JSX (which is even noted by the syntax highlighter). If you un-comment the variable's declaration, everything works as expected.

Here is index.js:

/*
Minimal non-Working Example of codesandbox CORS error
If you un-comment the declaration of `fail`, it works fine.
But for me, as is, it throws a cross-origin error,
on both Chrome and Firefox.
*/

import React from "react";
import ReactDOM from "react-dom";
import { Typography } from "@material-ui/core";

// const fail="error";

function Demo() {
  return (
    <Typography color={fail}>
      Cross-origin error demo
    </Typography>
  );
}

ReactDOM.render(<Demo />, document.querySelector("#root"));

And index.html

<body>
  <!-- Fonts to support Material Design -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
  <!-- Icons to support Material Design -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
  <div id="root"></div>
</body>

@iamandrewluca
Copy link

One more use case I encountered that throws A cross-origin error was thrown. When using a class before its declaration.

Does throw error

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(<App />, document.getElementById("root"));

class App extends React.Component {
  render() {
    return "The App";
  }
}

Does not throw

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  render() {
    return "The App";
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Keep in mind, a class not a function.

Much like their function counterparts, JavaScript class declarations are hoisted. However, they remain uninitialised until evaluation.
https://scotch.io/tutorials/understanding-hoisting-in-javascript

@handhikadj
Copy link

handhikadj commented Jan 4, 2020

confirmed on January 4th, 2020 on the latest React version (v16.12.0). come on, codesandbox. it's already 2020 and haven't solved yet.
this issue post must be bumped to the uppermost list

@CompuIves
Copy link
Member

Hey! I finaaaally found the issue after long debugging. I was confused, as the error never happened both on the PR builds and on dev. Initially, I thought this happened because of having self-signed certificates. But after verifying that the error even happens after using the right certificates, I started to look at other differences.

The difference turns out to be that sandboxes load their script files from the root domain (codesandbox.io), we do this to use the browser cache whenever possible. If you load 2 sandboxes then the second sandbox should load their files from cache. The tricky thing is that we only do this in production, not in our pr branch builds, not in our dev builds, not even in our local docker builds.

When looking at the React documentation I saw that using eval was discouraged, so I thought that the use of eval was the problem, and that we should find a different way of executing the code. This was the real distraction, because it turns out that using eval is not the problem, it's only a problem if the script that runs eval is from a different origin.

The errors started to show up correctly after adding crossorigin to the script files of the sandbox. So now everything is finally fixed! I'm sorry for the long time of the fix, the distraction on eval, combined with the fact that it could only be reproduced on codesandbox.io, caused me to take far too long.

TLDR: the problem was not using eval, the problem was the actual scripts that run eval were from a cross origin. It's now finally fixed!

@natkuhn
Copy link

natkuhn commented Jan 7, 2020 via email

@CompuIves
Copy link
Member

We are aware of this issue and we are working on it.

I agree, I need to work on our communication here. It's one of my intentions for 2020! 😄

@AndyOGo
Copy link

AndyOGo commented Jan 7, 2020

AWWEESSOOOMMEEE!!!!

@AlfredBryan
Copy link

Screenshot 2020-01-21 at 12 49 38 PM

@iamandrewluca
Copy link

Would be better to give some context first, we all know how error looks like 😄

@o-az
Copy link

o-az commented Jul 11, 2020

Still getting this issue.

@oskarabc
Copy link
Contributor

@Omar-Aziz, can you please post a link to whichever sandbox your using showing CORS errors?

@Samuel0941
Copy link

Samuel0941 commented May 25, 2021

error
Still showing error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet