Emulating a Javascript API request

I'm looking to practice simulating API calls for a VueJS application. Currently, I am fetching data from a hardcoded JSON file that I've created.

Within my App.vue:

<template>
  <p>{{ teams.yankees.city }}</p> // Output will be "New York"
</template>

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

  export default {
    data() {
      return { teams }
    }
  }
</script>

In my teams.json file:

{
  "yankees": [
    { "city": "New York", "established": 1901, "worldSeries": 27 } 
  ]
  ...
}

Although I can currently retrieve data from the local JSON file, I am interested in implementing "function stubs" to prepare for integrating real restful API calls in the future.

Is there a straightforward guide available that demonstrates how to set up a mock rest service to fetch data from my local JSON file?

Answer №1

If you're looking to utilize json files as mock data, all you need is a basic http server. Place your teams.json file in your project directory and use any http server of your choice to serve it. For example, you can use this simple, zero-configuration command-line http server.

After setting up the server, access your mock data using the Vue resource plugin:

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

To avoid hardcoding URLs in your service calls, consider creating a mapping file where you define resource "names" mapped to specific paths:

{
  teams: 'http://localhost:8080/teams.json'
}

This approach allows you to easily switch between different resource locations without modifying your core business logic.

If you require more advanced features, you can either develop them yourself or explore existing services such as mockable.io or apiary.io.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I enhance data from an AJAX callback in Mapbox with an additional layer?

With the code snippet below, I am aiming to utilize event data from an API to create a mapbox layer. This layer will be used to place markers and symbols on the map. However, I prefer not to use Mapbox markers as they cause issues with my code. I have suc ...

Exploring JQuery and JavaScript for loop guide

Currently working on a small application where users are required to input information, and I am implementing text hints in the input fields. However, I have encountered an issue when using a for loop in my code. Oddly enough, the text hints display corre ...

A guide on modifying environments in Angular

I am working on a project that involves 3 different environment files (dev, staging, production). I need to update these files for each dist folder accordingly (for example, when deploying to dev, I need the dev environment link to pull data from there, an ...

The issue of recursive updates is triggered by reactive props within Vue3 Treelist

I am currently utilizing vue3-tree for my project and I am attempting to set up the nodes. I am using pinia to store props.filter.data up to the parent component, but I am encountering this error: Uncaught (in promise) Maximum recursive updates exceeded. ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

What is the process for requesting a specific condition using jscript and jquery?

I'm experimenting with the following code: while (true) { $(document).ready(function() { setInterval(function () { if ($("h2").text() == "What is a light-year?") { $("#choice2").delay(200).queue ...

jQuery text replacement formatting

I need to strip parentheses and spaces from a field retrieved from JSON data. My initial approach was: '+myleads.Phone.replace(/(/g,'')+' However, repeating this process for each replacement seems cumbersome. Is there a simpler solut ...

Incorporate timing into character information/date and time

Recently, I've been working on passing a time stamp to my API. The timestamp is in the format of YYYY-MM-DD HH:MM:SS, but I need to adjust the time by adding 5 hours. I'm not sure if I'm doing this correctly. Should I convert it to a JavaSc ...

Tips on how to lock the ag-grid to the highlighted row's position and force it to scroll

We have integrated ag-grid into our system, and I am facing an issue with displaying the scrollbar in a child window based on the selected row position in ag-grid. Please refer to the Plunkr link below and click on source_id which will lead you to an edit ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

How can I make a polygon or polyhedron using Three.js?

Is it possible to generate polygon or polyhedron shapes in three.js using alternative methods? var customShapePts = []; customShapePts.push( new THREE.Vector2 ( -50, 200 ) ); customShapePts.push( new THREE.Vector2 ( 100, 200 ) ); customShapePts.push( ne ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

merging 4 arrays in a specified order, organized by ID

i have below 4 array objects var dataArray1 = [ {'ProjectID': '001', 'Project': 'Main Project 1', 'StartYear': '2023', 'EndYear': '2023', 'StartMonth': 'Sep&apo ...

Applying Media Queries Based on Element Height

Situation: In my scenario, there is an image with two buttons below it, all of which share the same width. Issue: When the viewport is too wide horizontally, the buttons are not visible without scrolling down. This poses a challenge for tablets and small ...

Combining arrays of objects in VueJS

I am working with 2 components: parent component (using vue-bootstrap modal with a vue-bootstrap table) child component (utilizing vue-bootstrap modal with a form) Issue: When I submit the form in the child component, it successfully adds the object to ...

having difficulty iterating through the data using map function

When attempting to use the map function in React Material UI to display an array of data in a select box, I encountered the error TypeError: Cannot read properties of undefined (reading 'map') while using the following code. Can anyone help me id ...

Issue encountered: Unable to fetch username and password from request

Currently, I am developing a login and registration system. However, when I input the correct details in my register Post method, the request remains pending and I cannot identify the error. The specific error message it presents is data and salt arguments ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...