ReactJS localhost Ajax call: No 'Access-Control-Allow-Origin' header

半世苍凉 提交于 2020-01-13 05:49:41

问题


Working on the ReactJS tutorial I spinned up a local server with

>npm install -g http-server

>http-server -c-1

And got local server working fine located at http://localhost:8080

Though, when I attempted to use an AJAX call within one of my components, I got the following error in my chrome console:

  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.

This is the ajax call snippet:

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 is coming from here:

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

回答1:


The header 'Access-Control-Allow-Origin': '*' needs to be on the server response to the AJAX request (not on the client request). Here is an example of doing that on vanilla NodeJS using http:

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);

For http-server, you can run it with --cors option.



来源:https://stackoverflow.com/questions/30824796/reactjs-localhost-ajax-call-no-access-control-allow-origin-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!