1

我想从拥抱服务器到 vue 客户端的 localhost API 获取数据。我在 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>

和这个拥抱的代码:

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

神秘地,当我applicacio.documents在 Firefox 控制台中咨询时,它得到了我undefined。这不是 CORS 问题,因为我api.http.add_middleware(hug.middleware.CORSMiddleware(api, max_age=100))在后端和<meta http-equiv="Content-Security-Policy" content="" />网页中添加。

4

1 回答 1

1

您可能想检查您的 api 响应。

特别是如果它在其 json 有效负载中具有属性“文档”。

.then(json => {
  // are we sure json includes a property documents?
  // maybe json is the array itself
  console.log(json) 
  this.documents = json.documents
})
于 2019-11-26T09:23:16.477 回答