ReactJS localhost Ajax调用:没有"Access-Control-Allow-Origin"标头 [英] ReactJS localhost Ajax call: No 'Access-Control-Allow-Origin' header

查看:80
本文介绍了ReactJS localhost Ajax调用:没有"Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ReactJS教程上,我使用

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

>npm install -g http-server

>http-server -c-1

并使位于 http://localhost:8080

但是,当我尝试在其中一个组件中使用AJAX调用时,在chrome控制台中出现以下错误:

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.

这是ajax调用代码段:

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来自这里:

this.props.url is coming from here:

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

推荐答案

标头'Access-Control-Allow-Origin': '*'必须在服务器上对AJAX请求的响应(不在客户端请求上).这是使用http在普通NodeJS上执行此操作的示例:

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

对于http-server,您可以使用--cors选项运行它.

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

这篇关于ReactJS localhost Ajax调用:没有"Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆