Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - React - component in seperate script does not work

I'm trying to learn react.js, but got stuck on "Hello World" script.

My index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://fb.me/react-0.13.3.js"></script>
    <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/jsx" src="src/helloworld.js"></script>
  </body>
</html>

and src/helloworld.js:

React.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

When I put this code inside <script> in index.html file it works fine, but when I move it to seperate file I get blank page, and console error:

XMLHttpRequest cannot load file:///home/marcin/Projects/react/src/helloworld.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

What is wrong with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You get that error because:

  1. You have loaded the index.html from your local file system (e.g. by double clicking on it), instead of loading it via a web server
  2. The JSX transformer, the one responsible of text/jsx scripts is a javascript component that tries to fetch the file specified by the src attribute of the script tag
  3. Javascript is allowed to fetch external resources only from the protocols enumerated in the error message (and even for those has further limitation like cross-domain requess); files loaded from the local file system have the file:// protocol which is not within that list.

When you included the jsx script in the index.html file it worked as no requests were needed in order to retrieve the jsx script.

What you need to do is grab your hands on a web server, place the hello world files into the document root of that server, and load them from the web server, e.g. from an URL like http://localhost/index.html.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...