在编写 ReactJS 教程时,我使用了本地服务器
>npm install -g http-server
>http-server -c-1
并让位于http://localhost:8080 的本地服务器正常工作
但是,当我尝试在我的一个组件中使用 AJAX 调用时,我的 chrome 控制台出现以下错误:
XMLHttpRequest cannot load http://localhost:8080/comment.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
这是 ajax 调用片段:
var CommentBox = React.createClass({
loadCommentsFromServer: function(){
$.ajax({
url: this.props.url,
dataType: 'json',
cashe: false,
crossDomain:true,
headers: {'Access-Control-Allow-Origin': '*'},
success: function(data){
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err){
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
this.props.url 来自这里:
React.render(<CommentBox url="http://localhost:8080/comment.json" pollInterval={2000} />, document.getElementById('content'));