Search code examples
javascriptvue.jshug

Vue.js return undefined data after CORS consult in hug server


I want to get data from localhost API from hug server to vue client. I have this code in vue.js:

        <div id="aplicacio">
        {{ documents }}
        <ul>
            <li v-for="document in documents">
                <a v-bind:href="document.path">{{ document.title }}</a>: {{document.text}}
            </li>
        </ul>
        </div>

    <script>
            var app = new Vue({
                el: '#aplicacio',
                data: {
                    documents: []
                },
                created () {
                    fetch('http://localhost:8000/documents/list')
                        .then(response => response.json())
                        .then(json => {
                            this.documents = json.documents
                        })
                }
            })
    </script>

and this code in hug:

import hug
api = hug.API(__name__)
api.http.add_middleware(hug.middleware.CORSMiddleware(api, max_age=100))


@hug.get('/documents/list')
def list():
    """Returns list of documents"""
    j = [{"text": "Hola", "path": "normativa.md", "title": "Normativa"}, {"text": "Això és una *activitat*", "path": "activitat1.md", "title": "Activitat 1"}]
    return j

Misteriously when I consult applicacio.documents in firefox console, it gets me undefined. It is not CORS problem, because I add api.http.add_middleware(hug.middleware.CORSMiddleware(api, max_age=100)) in the backend and <meta http-equiv="Content-Security-Policy" content="" /> in the web page.


Solution

  • You may want to check your api response.

    Especially if it has the property "documents" in its json payload.

    .then(json => {
      // are we sure json includes a property documents?
      // maybe json is the array itself
      console.log(json) 
      this.documents = json.documents
    })