Unable to retrieve information from the json-server

For my current project in Backbone.js, I'm utilizing the json-server package to populate it with data. I've created a db.json file containing the data and executed the command json-server --watch db.json. The server started successfully and is running on localhost:3000. In my Backbone application, the following code snippets are in place:

// app/javascripts/collections/resumes.js

define(['backbone', 'models/resume'], function (Backbone, Resume) {
    var ResumesCollection = Backbone.Collection.extend({
        model: Resume,
        url: 'http://localhost:3000/resumes'
    });
    return ResumesCollection;
});

// app/javascripts/views/resumes/resume.js

define(['backbone', 'jquery'], function (Backbone, $) {
    var ResumeView = Backbone.View.extend({
        tagName: 'article',
        render: function () {
            this.$el.html(this.model.get("firstName"));
            return this;
        }
    });
    return ResumeView;
});

// app/javascripts/views/resumes/index.js

define(['backbone', 'views/resumes/resume'], function (Backbone, ResumeView) {
    var ResumesList = Backbone.View.extend({
        tagName: 'section',
        initialize: function() {
            this.collection.fetch();
        },
        render: function() {
            var resumesView = this.collection.map(function (cv) {
                return new ResumeView({model: cv}).render().el;
            });
            this.$el.html(resumesView);
            return this;
        }
    });
    return ResumeList;
});

This is my app/router.js:

define(['backbone',
        'collections/resumes',
        'views/resumes/resume',
        'views/resumes/index'], 
function (Backbone, ResumesCollection, ResumeView, ResumeList) {
    var AppRouter = Backbone.Router.extend({
        routes: {
            'resumes': 'showAll'
        },
        showAll: function () {
            this.ResumeList.render();
        }
    });
    return AppRouter;
});

In app/javascripts/main.js, the configuration is as follows:

require.config({
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: [
                'underscore',
                'jquery'
            ],
            exports: 'Backbone'
        }
    },

    paths: {
        jquery: '../node_modules/jquery/dist/jquery',
        underscore: '../node_modules/underscore/underscore',
        backbone: '../node_modules/backbone/backbone'
    }
});

require(['backbone',
         'jquery',
         'router'
], function (Backbone, $, AppRouter) {
    var Router = new AppRouter();
    Backbone.history.start({
        pushState: true,
        root: '/'
    });
});

Additionally, I am using Gulp to run a development server on localhost:8080 using gulp-connect and gulp-livereload. However, when I try to access localhost:8080/resumes, I receive a Cannot GET /resumes message, despite no errors appearing in the console. What could be causing this issue?

Answer №1

I don't have the exact solution to the problem at hand, but I'll do my best to assist you.

Experimenting with json-server, I initiated it by setting up the db.json file as shown below:

{
    "posts": [{
        "id": 1,
        "title": "json-server",
        "author": "typicode"
    }, {
        "id": 2,
        "title": "This is a test",
        "author": "Emile Bergeron"
    }]
}

Subsequently, I created a basic collection for utilization.

var PostCollection = Backbone.Collection.extend({
    url: "http://localhost:3000/posts"
});

var posts = new PostCollection();
posts.fetch({
    success: function(){
        console.log(posts.pluck('title'));
    }
});

Upon checking my console, I observed:

["json-server", "This is a test"]

Navigating through this process was surprisingly hassle-free! However, the issue might lie elsewhere. It could be beneficial to provide the complete request details (raw data).


Retrieving a collection

this.collection.fetch(); // this is sufficient

The inclusion of

{ data: { fetch: true, type:"get" } }
is unnecessary since it's the default functionality.

Linking function calls

There's a risk of failure in the following line within ResumeList:

return new ResumeView({model: cv}).render().el;

This is due to the fact that the render function in ResumeView doesn't return this.


Overall, your code appears to be in good shape.

If you plan on placing the API on a different server, potentially involving a separate domain, familiarize yourself with CORS, essential for enabling JavaScript to fetch data from distinct domains.

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

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

Angular Nested Interface is a concept that involves defining an

Looking for guidance on creating a nested interface for JSON data like this: Any help is appreciated. JSON Structure "toto": { "toto1": [], "toto2": [], "toto3": [], } Interface Definition export interface Itot ...

Having trouble setting up npm package (fsevents) on Mac OS Catalina?

I'm facing an error when trying to run the npm install express --save command. Can someone assist me in resolving this issue? The error message is as follows: > email@example.com install /Users/delowar/Desktop/ytdl/node_modules/chokidar/node_modu ...

How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest? var json = { // JSON data goes here } json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(it ...

Working with a function that has a changing parameter for each iteration [python]

Need help with a Python task involving filtering a list stored as a json array using another list of lists containing dictionaries. The goal is to write a function that filters the list based on the criteria from these three lists, but encountering an issu ...

JavaScript ES6 array method for generating an object from an array

I wish to transform the following array: [ { event: "LIB", block_calendar: "YES", obs: "Lorem Ipsum", status: "Block", }, { event: "LIB" block_calendar: "YES" o ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

`On mobile devices, the Bootstrap button no longer displays focus changes once clicked.`

When clicking a primary bootstrap button, it changes its background color to blue on mobile devices. https://i.sstatic.net/VNPDP.jpg For example, the first button appears normal and the second one turns blue after clicking. However, this background effec ...

Signal for a complete 360 degree rotation of an image

Looking to enhance my 360 image rotator with an indicator that fades out after the first image. I added this function to the end of my 360.js: (function(){ if( $('#first').css('visibility','hidden')) { $('#rotat ...

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

Avoiding the duplication of selected items in a dropdown within a gridview can be achieved effectively by implementing a JavaScript/jQuery

In my gridview, which contains multiple rows, each row has a dropdown (select in HTML). My goal is to prevent the user from selecting the same item from the dropdown list for different rows. For instance, if a user selects "New York": Assigning rooms: U ...

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

Exploring the process of integrating absolute paths within a global SCSS file in a VueJS project

The webpack configuration in my vue.config.js file looks like this: const path = require("path"); module.exports = { pluginOptions: { 'style-resources-loader': { preProcessor: 'scss', patterns: [ "./src/style ...

Retrieving data from a collection with the find() method in a custom date format

Schema for Customer Data Customers.js import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, Pho ...

Rendering Nested JSON Data from Node.js to EJS Template

I find myself lost in a sea of browser tabs, with 1000 open and still unable to locate the information I need. server.js When it comes to fetching data from my neo4j database in the server, this is what I have running: app.get('/ios', async (r ...

Encountering "SyntaxError:" due to an unexpected token in the JSON data at the beginning while trying to parse with JSON.parse

Encountering a "SyntaxError:" Unexpected token in JSON at position 0 when fetching compressed data from backend Spring Boot in Angular 7 On the backend, I am compressing a list of objects using the following structure: ArticleObj.java public class Articl ...

Utilize Material-UI slider components to dynamically manage slider handles

I am trying to dynamically create sliders based on user input and struggling with saving values when they are changed. Below is the code snippet I have implemented so far. The issue I'm facing is that I cannot retrieve the value using event.target.val ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...