Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Javascript模拟API调用_Javascript_Json_Rest_Api_Vue.js - Fatal编程技术网

用Javascript模拟API调用

用Javascript模拟API调用,javascript,json,rest,api,vue.js,Javascript,Json,Rest,Api,Vue.js,我想模拟一个API调用。我正在用VueJS编写一个应用程序,目前正在从我创建的硬编码JSON文件中检索数据 例如,从myApp.vue: <template> <p>{{ teams.yankees.city }}</p> // Will output "New York" </template> <script> import teams from './teams.json' export default {

我想模拟一个API调用。我正在用VueJS编写一个应用程序,目前正在从我创建的硬编码JSON文件中检索数据

例如,从my
App.vue

<template>
  <p>{{ teams.yankees.city }}</p> // Will output "New York"
</template>

<script>
  import teams from './teams.json'

  export default {
    data() {
      return { teams }
    }
  }
</script>
我现在可以从本地JSON文件中成功地检索到数据,但是我如何使用“函数存根”来检索数据,以使我能够在将来交换真正的restful API调用呢


某个地方有没有介绍如何设置调用本地JSON文件的模拟rest服务的裸体资源?

要使用JSON文件作为模拟数据,您只需要一个简单的http服务器。将teams.json文件放在项目目录中的某个位置,并使用您选择的http服务器为其提供服务,例如:

然后使用插件访问模拟数据:

我猜您不想在服务调用中硬编码URL。我喜欢做的是创建一个映射文件,在其中定义资源名称并将它们映射到具体路径:

{
  teams: 'http://localhost:8080/teams.json'
}
这样,我可以在不同的资源位置之间切换,而无需更改业务代码

如果您需要更复杂的东西,您可以自己构建它,或者查看现有的服务,例如

{
  this.$http.get('http://localhost:8080/teams.json').then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}
{
  teams: 'http://localhost:8080/teams.json'
}