Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ReactJS localhost Ajax调用:No';访问控制允许原点';标题_Javascript_Ajax_Node.js_Localhost_Reactjs - Fatal编程技术网

Javascript ReactJS localhost Ajax调用:No';访问控制允许原点';标题

Javascript ReactJS localhost Ajax调用:No';访问控制允许原点';标题,javascript,ajax,node.js,localhost,reactjs,Javascript,Ajax,Node.js,Localhost,Reactjs,在编写ReactJS教程时,我启动了一个本地服务器 >npm install -g http-server >http-server -c-1 并使位于的本地服务器正常工作 但是,当我试图在我的一个组件中使用AJAX调用时,我在chrome控制台中遇到了以下错误: XMLHttpRequest cannot load http://localhost:8080/comment.json. No 'Access-Control-Allow-Origin' header is p

在编写ReactJS教程时,我启动了一个本地服务器

>npm install -g http-server

>http-server -c-1
并使位于的本地服务器正常工作

但是,当我试图在我的一个组件中使用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)
                        });
                    },
此.props.url来自此处:

React.render(<CommentBox url="http://localhost:8080/comment.json" pollInterval={2000} />, document.getElementById('content'));
React.render(,document.getElementById('content');

'Access-Control-Allow-Origin':“*”
需要位于服务器对AJAX请求的响应上(而不是客户端请求上)。下面是一个使用
http
在普通nodej上执行此操作的示例:

var http = require('http');

var server = http.createServer(function(request, response) {
  response.writeHead(200, {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'
  });
  response.end('hi');
}).listen(8080);

对于
http服务器
,可以使用
--cors
选项运行它。

可以发布服务器端点代码吗?问题是
访问控制允许源代码的头需要在服务器响应上。这更有意义。使用
http服务器
,我将如何实现这一点?comment.json是否只需要返回标题?您可以展示一个javascript示例吗?@ApathyBear您可以使用
--cors
运行
http服务器
,以启用cors头。如果这还不够帮助的话,你应该发布你的服务器或你正在使用的特定教程的链接。
http服务器-c-1--cors
非常有效。非常感谢。