为什么我的AJAX请求没有通过?

时间:2019-03-17 13:53:45

标签: node.js ajax reactjs post flask

This是我目前正在进行的this现场演示的github存储库。

// index.js是发送POST请求的位置

class Index extends React.Component {
    state = {
        loading: false,
    };

    handleClickLoading = () => {
        this.setState(state => ({
            loading: true,
        }));
        var jqXHR = $.ajax({
            type: "POST",
            url: "http://localhost:5000/login",
            async: true,
            data: { mydata: [Cookies.get('links'), Cookies.get('numSentences')] },
            success: function(){
                const data = JSON.parse(jqXHR.responseText);
                console.log(data);
            }
        });
        Cookies.set('final', jqXHR.responseText);
        console.log(jqXHR.responseText)
    };

    render() {
        const {loading} = this.state;
        return (
            <div>
                <AppBar/>
                <Block/>
                <Card>
                    <CardActions>
                    <Button size="large"
                            fullWidth={true}
                            onClick={this.handleClickLoading}>Submit</Button>
                    </CardActions>
                </Card>
                <Fade
                    in={loading}
                    unmountOnExit
                    >
                <BottomBar/>
                </Fade>
            </div>

        )
    }
}

export default Index;

并尝试通过Flask服务器通过python脚本获取数据:

...
def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, list):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, list):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator


@app.route("/")

def home():
    return "hi"
@app.route("/index")


@app.route('/login', methods=['GET', 'POST', 'OPTIONS'])
@crossdomain(origin='*')
def login():
   message = None
   if request.method == 'POST':
        datafromjs = request.form['mydata']
        result = "test"
        resp = make_response('{"response": '+result+'}')
        resp.headers['Content-Type'] = "application/json"
        resp.headers.add('Access-Control-Allow-Origin', '*')
        resp.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        resp.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return resp
        return render_template('login.html', message='')

if __name__ == "__main__":
    app.run(debug = True)

这是浏览器的控制台输出onClick: enter image description here

和烧瓶:

enter image description here

javascript尝试在给定一些参数的情况下获取一些python函数的输出。

我在这里陷入僵局,这是我项目中的最后一个齿轮。我以前没有这类经验,但是可以提供任何帮助!

1 个答案:

答案 0 :(得分:0)

我相信这是一个CORS问题,就像JJ Hakala指出的那样。即使您要使用相同的域(本地主机),但使用不同的端口(8080-> 5000),也需要存在授权标头(服务器端)。

如果您可以确保服务器响应中存在标头from operator import itemgetter iget = itemgetter('first_name') set(map(iget, data)) # {'Mary', 'John'} (通配符域方法),那么您就不会再遇到Ajax问题。

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

相关问题