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

9.8k Views Asked by At

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

There are 1 best solutions below

3
On BEST ANSWER

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.