如何设置快速路由 res.json(data) 对象并在 vue $HTTP 调用中显示响应?

How to setup express route res.json(data) object and display the response in vue $HTTP call?

集合中的实际数据

使用快递: 具有 mongodb 个集合的 Mongoose 模型称为 "comments"

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Comment = new Schema({
title : String,
});
mongoose.model('comments', Comment);
mongoose.connect('mongodb://localhost/test');

我的获取路线:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('comments');


/* GET form. */
router.get('/', function (req, res) {
Comment.find(function (err, comments) {
    res.json(comments);
});
});

我的 front.html 使用 vue 和 vue 资源

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">


<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js">  `   `</script>`
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script> 
<title>$http access to express route</title>
</head>
<body>
<h1>
    <a href="http://localhost:1337"> Front page</a>
</h1>

<div id="app">
    <ul>
        <li v-for="item in items">
            {{ item.title }}
        </li>
    </ul>
</div>

<script>
    new Vue({

        el: '#app',

        data: {
            items: []
        },

        created() {
            this.fetchData()
        },

        methods: {
            fetchData() {
                this.$http.get('http://localhost:1337/form')
                  .then(result => {
                      this.items = result.data
                  })
            }
        }

    });
</script>

</body>
</html>

评论没有显示在我的 vue 标签中。访问表达发回的 Comment.find(err, comments) 对象的正确方法是什么?当我使用像 (https://jsonplaceholder.typicode.com/users) 这样的测试 api 时,vue 资源 $http 正在工作,但是当我尝试访问我的路由 localhost:1337/form 路由时,它没有显示任何内容。需要熟悉快速路线、vue 的人。我无法在网上找到任何详细演示此示例的示例。好像网上所有的教程都跳过了这部分

我是否需要 return 我的路线中的结果采用不同的格式?我是否需要将结果添加到 var 以便我可以通过 $http 访问?我需要更改我的快递路线吗?

如果有人有一个活生生的例子。 post 一个 link.

就好了

这是因为你的 this 没有指向正确的范围,这个范围在 this.$http 调用中发生了变化,所以你只需要做如下的事情:

    methods: {
        fetchData() {
            var self = this
            this.$http.get('http://localhost:1337/form')
              .then(result => {
                  self.items = result.data
              })

你也可以看看我类似的回答 and here

正在查看 JSON 数据,发现您没有评论 属性 作为回应。

尝试改变这个:

<div id="app">
    <ul>
        <li v-for="item in items">
            {{ item.comments }}
        </li>
    </ul>
</div>

至此

<div id="app">
    <ul>
        <li v-for="item in items">
            {{ item.title }}
        </li>
    </ul>
</div>

您应该会在页面上看到您的数据。

快速路由句柄需要 return 以 json 格式响应,因此请这样写您的路由:

res.json(响应对象)

在您的 html Vue 标签中,按照示例中的代码更改 {{item.fieldname}} 以显示您需要显示的任何字段名称。

此答案归功于@Belmin。