Вопрос

Bakground

I have a bit of a chicken and egg problem:

Question

Please help me understand why:

I realize plunkers are popular; however, the demo webapp plunker is not helping because I can't get it to behave as my webapp does; I literally copied the HTML straight off my demo webapp into the plunker. Perhaps I am doing something wrong, but I need help understanding what I've done wrong (if anything).

Explicit resolution

I'm using Flask + Python to render the json data... the explicit fix was...

from functools import update_wrapper
from datetime import datetime, timedelta
from json import dumps

from flask import Response, Flask, redirect, url_for, abort, render_template, flash
## Other imports here...

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, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        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

### Use @crossdomain() decorator to fix my plunker's ajax request
@app.route('/demo/api/v1/data01', methods=['GET'])
@crossdomain(origin='*')
#@login_required
def send_all_tasks():
    """Send all tasks back to AngularJS"""
    retval = [
        {'Column02': 'shines', 'Column03': 'paycheck', 'Column01': 'days'},
        {'Column02': 'erg', 'Column03': 'gag', 'Column01': "emotion's"},
        ]
    return Response(dumps(retval), mimetype='application/json')
Это было полезно?

Решение

Welcome to the world of Cross Origin Resource Sharing. If you check the console in your plunkr, you will see that the ajax request for your json is failing with the following error...

XMLHttpRequest cannot load http://demo.pennington.net/demo/api/v1/data01. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://run.plnkr.co' is therefore not allowed access. 

By default, only pages served by your domain (demo.pennington.net) can make ajax calls to your domain. This is for security purposes. You can configure your server to allow requests from plunkr.co by setting an 'Access-Control-Allow-Origin' header with the value of plunkr.co like the error message states, however this would allow anyone who creates a plunkr to send ajax requests to your site. This is not very secure. If I were you, I would just hardcode the json in your plunkr and remove the ajax request.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top