从 localhost 迁移到服务器后,如何不丢失 json 中的 get?

How not to lose a get in json after migrating from localhost to server?

我正在本地主机上使用 .json 文件,一切正常。但是,现在我想部署,localhost 将不再工作。

这是部分代码:

// BurgerForm.vue

methods: {
  async getIngredients() {

    const req = await fetch("http://localhost:3000/ingredients");
    const data = await req.json();

    this.breads = data.breads;
    this.meats = data.meats;
  },
…
}

为了让我 运行 localhost 我 运行 在我的 package.json 以下后端:

"scripts": {
  "serve": "vue-cli-service serve",
  "build": "vue-cli-service build",
  "backend": "json-server --watch db/db.json"
},

我提到的文件结构是这样的:

/db/db.json

/src/components/BurgerForm.vue

那么迁移到服务器后如何继续从json查询和获取数据呢?

您可能会发现 Webpack Dev Server 有用。

假设您不介意在主系统的某个路径下提供您的 API,如果您将以下内容添加到您的 vue.config.js

devServer: {
   //...other options may be necessary
   proxy: {
        "/path/to/api/*": {
             target: "http://localhost:3000",
             secure: false,
             changeOrigin: true
        }
   }
}

使用 npm run serve 启动前端应用程序后,如果您向针对同一服务器的 /path/to/api/ingredients 发出请求,即 fetch("/path/to/api/ingredients"),开发服务器将代理自动请求 http://localhost:3000/ingredients