codesandbox / codesandbox-client

An online IDE for rapid web development
https://codesandbox.io
Other
13.11k stars 2.29k forks source link

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

Closed mescalito closed 4 years ago

mescalito commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

@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 commented 6 years ago

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

boscorona commented 6 years ago

@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 commented 6 years ago

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 commented 6 years ago

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

meetzaveri commented 5 years ago

@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 :raised_hands:

AndyOGo commented 5 years ago

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 commented 5 years ago

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

AndyOGo commented 5 years ago

@lbogdan I hope so too, but I experienced the bug yesterday πŸ€”

lbogdan commented 5 years ago

Looks like I got lost in the unrelated comments, and missed the actual issue πŸ™‚ , reopening.

CompuIves commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

CompuIves commented 5 years ago

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 commented 5 years ago

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

No and yes

AndyOGo commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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

AndyOGo commented 5 years ago

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: https://github.com/facebook/react/issues/10441

AndyOGo commented 5 years ago

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 commented 5 years ago

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

SHoar commented 5 years ago

@robertkofoed this temporary work-around is not something a general user is able to do during their codesandbox.io session. It is a react/webpack issue.

The issue is when using the provided react/react-dom dependencies from the create-react-app generated react sandbox, the user is unable to edit any of the webpack config files. As @CompuIves mentioned, it is a code execution issue, where CodeSandbox uses eval to evaluate code, and if a user has used CRA using the template for a react sandbox, this is not something the user can change. @CompuIves had mentioned using cdn scripts to provide react/react-dom, but the scale switch is very daunting. Is there any way to enhance error boundary notices to tell the user to try binding methods to components or telling them that they should try creating a generic sandbox and then adding webpack, react, reactdom, .... as I'm typing this, I realize that I don't want to do that, and I'm sure most other users are not going to want to do that.... A fix for this is requested still.

Sidenote: I also received this react cross-origin error when trying to wrap THREE.js inside a React component.

cziem commented 5 years ago

As at this minute am still getting the same error.

lbogdan commented 5 years ago

@phavor Replied on Twitter. πŸ™‚

AndyOGo commented 5 years ago

@lbogdan @CompuIves Did you have any chance to look into setting Content-Securty-Headers for script-src at your servers? https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

AndyOGo commented 5 years ago

@lbogdan @CompuIves Here is another great article about CSP: https://developer.chrome.com/extensions/contentSecurityPolicy#JSEval

CompuIves commented 5 years ago

I think the only way of fixing this issue is by not using eval or Function for loading the JS bundle of React. If we load it using eval or Function React doesn't have access to the error stacktrace, which is the root cause of the issue.

The easiest fix for this, since React is the only library with this issue, is to add an override and specify that for React we load the UMD bundle from unpkg.com. This will make it possible for React to see the stacktrace and shouldn't change the behaviour for the user. I'll put it on my list, hopefully I can have something ready today.

AndyOGo commented 5 years ago

@CompuIves @lbogdan According to the Content Security Policy spec, a <meta> tag can also be used to set script-src πŸŽ‰ Like:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval'">

That doesn't even need a server change and would cover all cases, not only React.

stnwk commented 5 years ago

Would be super nice to have solution for this…

I'm trying to showcase an error in some other OSS library and went on to use codesandbox to provide a reproducable case, only to realise it doesn't show the error at all, but instead I got hit with the masked error described in here :/

jonnyasmar commented 5 years ago

Haven't really investigated why or in much depth, but thought it might be worth mentioning that I experience this problem with react/react-dom 16.9.0, but not 16.8.4.

lintonye commented 5 years ago

Yup got the same issue with React 16.9.0 too: https://codesandbox.io/s/codesandbox-cross-origin-error-usxnb

leonbrag commented 5 years ago

I have the same error in code here: https://codesandbox.io/s/reactjs-popup-issue-template-f8ibg. Not using component in the render() methods seems to fix problem.

However wrapping AudioCalibrator component in Popup works perfectly: https://codesandbox.io/s/reactjs-popup-issue-template-2dr8e

no-1ne commented 5 years ago

https://github.com/codesandbox/codesandbox-client/pull/1711 does this resolve the issue?

AndyOGo commented 5 years ago

@startupgurukul no #1711 does not 😞

Anyway I would really like to go with CSP headers:

According to the Content Security Policy spec, a <meta> tag can also be used to set script-src πŸŽ‰ Like:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval'">

That doesn't even need a server change and would cover all cases, not only React.

But this has to be done either at the servers or with above <meta> tag

no-1ne commented 5 years ago

The error has been there from a long time and reactjs offical page seems to be using codepen for examples now, sad to see such a well-architected solution not getting much love

perich commented 5 years ago

Got this issue with React 16.9

Downgraded to React 16.8.6 and the issue no longer manifests on Codesandbox

alesmenzel commented 5 years ago

Just got the error out of a blue: https://6gtpg.csb.app/ Is there any workaround or can we get any ETA on when this will be fixed?

alexdevero commented 5 years ago

I ran into this issue as well with React 16.11.0.

madrus commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

I just created a PR #3098 to set proper Content Security Policy to fix React's cross-origin error.

@mescalito @nbosco @alexdevero @shrutikapoor08 @startupgurukul @chintanvyas360 @leonbrag @CompuIves @lbogdan I would be happy if we can collect your reproduction examples and check if they work now.

I used following reproduction examples:

jdolearydl commented 4 years ago

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 commented 4 years ago

@jdolearydl

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

alundiak commented 4 years ago

@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).