【问题标题】:How do I connect express to vue app with axios如何使用 axios 将 express 连接到 vue 应用程序
【发布时间】:2020-04-28 15:50:03
【问题描述】:

我正在尝试将我的本地 express api 连接到我的 Vue 应用程序。当我在浏览器中转到“http://localhost:3000/all”时,它会按预期显示数组“myArr”值。但是我无法让 Axios 在我的 Vue 脚本中返回数组值,我不断收到类似“TypeError: Cannot read property 'get' of undefined”的错误。

我一直在寻找一段时间没有运气。我找到了一些提供处理 cors 解决方案的线程,但我无法让其中任何一个工作。

如何让“myArr”值显示在我的 vue 应用程序中?


这是我的 Express 脚本:

const express = require('express');

const myArr = ["one", "two", "three"];

console.log("server is starting");
const app = express();
const server = app.listen(3000);

app.get("/all", function sendAll(req, res) {
  res.send(myArr);
});

这是我的 Vue 脚本:

<template>
  <div class="container">
    <p>test</p>
    <p class="error" v-if="error">{{ error }}</p>
    <div class="item-container">
      <div
        class="items"
        v-for="(myItem, index) in myItems"
        v-bind:item="myItem"
        v-bind:key="index"
      >
        <p>{{ myItem }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { axios } from "axios";
export default {
  name: "vue-app",
  data() {
    return {
      myItems: [],
      error: ""
    };
  },
  async created() {
    const res = await axios.get("http://localhost:3000/all");
    this.myItems = res.data;
  }
};
</script>
//style

如果我可以提供更多信息,请告诉我,我感谢任何/所有帮助:)

【问题讨论】:

    标签: typescript express vue.js axios


    【解决方案1】:

    现在 axios 的平均值是 undefined
    解决方案:
    替换import { axios } from "axios";
    import axios from 'axios';

    【讨论】:

    • 感谢您的评论 - 我认为这不起作用。
    • 啊,评论后我开始工作了!我认为这是问题之一,感谢您的帮助!
    猜你喜欢
    • 2013-01-09
    • 2015-05-18
    • 2019-07-18
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多