Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model.

Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but

console.log(todoItem.get('description'))
returns undefined.

In most Backbone applications, omitting the extension .json seems common e.g. urlRool: "/todos" rather than urlRoot: "/todos.json", yet errors are experienced without the extension.

  • Seeking guidance on correct use of url and urlRoot properties.
  • Interested in learning about implications of not using .json or including it.
  • Lastly, seeking feedback on whether the JSON file format below is suitable for Backbone?

Backbone:

(function(window, $, Backbone) {
    var TodoItem = Backbone.Model.extend({ urlRoot: './js/json/todos' });

    var todoItem = new TodoItem({id: 1});

    todoItem.fetch();

    console.log(todoItem.get('description')); // Returns undefined

}(window, jQuery, Backbone));

JSON:

{
    "todos": [
    {
        "description": "Pick Up Milk",
        "status": "incomplete"
    },

    {
        "description": "Do shopping at Market",
        "status": "incomplete"
    }]
}

Answer №1

The reason why you see it without the .json extension is because the backend of the website is configured to return JSON data without the .json extension in the URL. When working with a static JSON file, you simply need to add .json to the file name.

It ultimately depends on how the server is set up and what is handling the URLs.

In terms of formatting, there is no need for the curly braces {}. It can be formatted as follows:

[{
    "description": "Pick Up Milk",
    "status": "incomplete"
},

{
    "description": "Do shopping at Market",
    "status": "incomplete"
}]

When using a static JSON file, I handle the GET request manually like this:

$.ajax("./js/json/todo.json").done(function(data) {
    // Here, I am using extend to add an id, but you could also just use data[0]
    var todoItem = new ToDoItem(_.extend(data[0], { id: 1 }));
}

If your JSON file contains a collection of items, Fetch may not work effectively. Instead, you can create a Backbone Collection like this:

var ToDoCollection = Backbone.Collection.extend({
    model: ToDoItem,
    url: "./js/json/todo.json"
});
var toDos = new ToDoCollection();
toDos.fetch();

This approach should provide you with a collection where each entry corresponds to a model in the JSON file.

Answer №2

It is irrelevant whether you are utilizing .json or not, as long as the endpoint exists. Therefore, if your file is named todo.json, it must contain .json. A simple method to verify this is by copying and pasting the file's URL into your browser and ensuring it displays correctly.

The reason for receiving undefined may be due to the structure of your JSON file. At the top level of the object, there is no description. Backbone anticipates an array of Models, not an object that holds an array of Models. For instance:

[{
    "description": "Pick Up Milk",
    "status": "incomplete"
},
{
    "description": "Do shopping at Market",
    "status": "incomplete"
}]

url pertains to a collection, while urlRoot pertains to an individual model. This allows for the creation of a logical naming convention. For example, when accessing an API, I might use the following framework:

GET /todos - Retrieve all todos
GET /todo/:id - Retrieve one todo

This can be achieved by defining the url as /todos and the urlRoot as /todo. Backbone will automatically attach the ID. It is important to note that while urlRoot is optional, url must be specified.

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

"An error was encountered with the JSON acceptance due to an

When I call an external json API, the response is coming back as JSON. If I don't specify the datatype as JSONP, the API fails due to an access control issue. I can successfully hit the API with Postman and receive the response. However, in the conso ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Obtaining the domain from a cookie using AngularJS

I've encountered a issue with removing cookies from my browser when logging out. It seems that I need to specify the domain in order to remove them correctly. $cookies.remove('Name',{domain:'.test123.com'}); My goal is to automat ...

Efficiently uploading multiple files using AJAX in conjunction with Codeigniter

Greetings! I'm attempting to utilize ajax and codeigniter to upload multiple images. As a beginner in ajax and jquery, I would greatly appreciate any assistance in identifying where I might be going wrong or missing something. Below is my controller ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

Tips on serializing the list property of a dynamic object

Encountering a serialization issue with a WCF service that outputs JSON. I am using DynamicObject to generate lightweight JSON for my REST service. The following code returns an empty result and cannot be serialized: public DynamicJsonObject DoWork() { ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

Struggling to utilize the filter technique in JavaScript?

Hey there, I'm facing a challenge in my JavaScript course. The exercise requires the creation of a function that filters an array to only keep strings with less than 10 characters. I've made several attempts at solving this problem, but haven&ap ...

The kendo-ui numeric textbox is malfunctioning when set with a step value of 0.001

Having some issues with the Kendo UI numeric text box. Specifically, it doesn't seem to work properly when using a step value of 0.001. In the example code snippet below, I managed to get it to increment by 0.001 with HTML5 but couldn't make it w ...

"Trouble with JavaScript boolean values in if-else conditions - not functioning as expected

While utilizing true/false values and checking if at least one of them is true, I am encountering an issue with the if/else statement not functioning as expected. Here is the code snippet: $scope.checkValues = function (qId) { var airport = $scope.air ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

Dealing with problems in col-md display on tablet devices

When viewing on Full Screen and mobile, the ranges panel (class="col-md-3") displays correctly. However, on tablet screens, the left column is obscured by the youtube image panel (class="col-12 col-md-9"). I have attempted various adjustments to the div s ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...

Tips for utilizing multiple checked data bindings with a single radio button in KnockoutJS

Ensure the user selects a single radio button. The label needs to display the value of the selected radio button in a text box and store it in the Ajax "title" variable for backend use (Python - Flask). Clicking the migrate button triggers the Ajax call. ...

Are you familiar with the Puppeteer PDF tool that generates empty pages from the cloud and seamlessly integrates with Postman? What do

After days of searching, tweaking, and deploying, I still can't get this to work. I'm hoping it's just a simple mistake on my part that someone else can help me with. I am attempting to use Puppeteer to generate a PDF from a Node.js Express ...