Angularjs is capable of successfully performing GET requests with JSON data, but encountering difficulties when trying to execute

I'm still getting the hang of using angularjs. I've been working with some JSON data and running into an issue with my post command. The get request is functioning perfectly, but any other type of request results in a 404 url error even though I've double-checked that everything matches up.

Below is my app.js code that includes the working get command:

angular
.module('app', [
    'ui.router'
    ])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('home', {
            url: '/',
            templateUrl: 'templates/home.html',
            controller: 'homeCtrl',
            resolve: {
                friends: ['$http', function($http){
                    return $http.get('./api/friends.json').then(function(response ){
                        return response.data;
                    })
                }]
            }
        })
        .state('about', {
            url: '/about',
            templateUrl: 'templates/about.html',
            controller: 'aboutCtrl'
        })
        .state('contact', {
            url: '/contact',
            templateUrl: 'templates/contact.html'
        })
}])

I also have the homeCtrl.js file which handles content loading for the home page, where my goal is to edit the page contents and save them back to the JSON file.

However, when attempting to use the post command, it leads to a 404 error.

angular
.module('app')
.controller('homeCtrl', ['$scope', 'friends', '$http', function($scope, friends, $http){
        $scope.title = "Home";
        $scope.friends = friends;
        $scope.items =['item1', 'item2','item3'];
        $scope.selectedValue = 'item1';

        $scope.save = function() {
            $http.post('./api/friends.json', friends);
        };
}]);

The following is the HTML content for home.html:

<h1>{{title}}</h1>
<ul>
    <li ng-repeat = "friend in friends">
        <input type="text" ng-model="friend.name">
        <input type="text" ng-model="friend.age">
    </li>
</ul>
<button ng-click="save()" class="btn btn-primary">Save</button>

Lastly, here is the content of the friends.json file:

[
    {"name": "Will", "age": 30},
    {"name": "Laura", "age": 25}
]

Answer №1

You mentioned your desire to modify the content of the homepage and then save it back to the JSON file.

Angular does not have the capability to save directly to local files. The "Get" request works because the browser can load static files like CSS or HTML.

If you are running your application by just clicking on the HTML file and not using an HTTP server, you will face a 404 error. To avoid this, run a server (such as Node.js HTTP server) in the folder and connect your browser to it. Although this method won't update the JSON file.

If saving data is essential, you'll need a fully functional application with API support to process requests and store data efficiently.

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

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

The absence of button.onclick=func in the HTML code is notable

I am facing an issue where adding an onclick attribute to an input element via JavaScript does not display in the HTML, but the function gets executed. On the other hand, when I add the input element directly in the HTML code, the onclick attribute shows u ...

Tips for dynamically adjusting image size while maintaining its aspect ratio using javascript

I am trying to achieve image resizing and displaying functionality using Javascript without jQuery. I currently have a "file" input with an onchange event that triggers a function called readURL. Although the current implementation resizes and displays the ...

Learn how to send a POST request in a loop using React

I've created a function to delete all elements in a table using the rowKeys array. The current contents of rowKeys are ["www.google.com", "www.youtube.com", "www.facebook.com"]. async onAfterDeleteRow(rowKeys) { for(let i = 0; i < rowKeys.leng ...

Can the website be inaccessible to human users in any way?

In my PHP programming journey, I encountered a challenge that I need help with. I created a function to retrieve data via ajax in my PHP code, but realized that users can manipulate the site by manually entering the ajax request link or altering its valu ...

Can AngularUI typeahead be used with the orderBy function?

This query is connected to a previous inquiry I made. You can find it here. I have successfully implemented AngularUI Typeahead. However, my orderBy filter seems ineffective. The select box arranges items correctly (distance is a custom function): <s ...

Issues with AngularJS Drop Down Validation Failure

When I submit my AngularJS form, only one of the drop down lists is showing the required validation. The drop down lists have a difference in their source - one uses an object to set the option label and values, while the other uses a standard dimensional ...

Tips for extracting the most deeply nested object in a JSON file using JavaScript

Is it possible to access the innermost object without knowing the path names? Consider this JSON example: const data = { first: { second: { third: {innerObject} } } ...

Error encountered when launching React application on IE11: SCRIPT1010- Identifier expected

Currently, I am developing a React application using webpack and babel. One issue that has cropped up is the appearance of "SCRIPT1010: Expected identifier" error messages when running it on IE11. To address this, I have managed to resolve most of these er ...

Transferring an image from a canvas in Windows 8.1

Recently, I've been working on developing a paint program for Windows 8 using JavaScript. However, I have encountered a setback. I am struggling with the process of exporting an image from a canvas. While I am somewhat familiar with the FileSavePicker ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

In Javascript, swap out a particular colored region in an image with a different image

I've been scouring the internet in search of a solution to my problem, but it seems like I might not be looking in the right places. Imagine this image below, how can I replace the blue area with an image uploaded by the user? I'm struggling to ...

How to Retrieve a Specific Line with jQuery

Could jQuery be used to retrieve the offset of the first letter in the 5th visual line of a block's content? I am referring to the visual line determined by the browser, not the line seen in the source code. ...

Tips for managing React state when dealing with multiple axios callbacks that modify an array's state

I am currently working on a React component that allows users to upload images. In this scenario, I aim to upload 3 images. After each file is uploaded, I want to append it to the list of uploaded files. Issue: The setter method in useState is asynchronou ...

When incorrect credentials are entered, consider displaying toast notifications in the login screen

<button type='submit' action='#' class='btn btn-primary block full-width m-b' id='showsimple1'>Login</button> $name = $_POST['name']; $password = $_POST['password']; if(!($usr = $db ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

Customizing the Mui Theme in a Unique Way

After generating an MUI component from Mui DatePicker, I encountered the following code: <span class="my-theme-MuiTypography-root my-theme-MuiTypography-caption my-theme-MuiDayCalendar-weekdayLabel css-1mln09i-MuiTypography-root-MuiDayCalendar-week ...

What is the method for consistently rotating the object regardless of the camera's orientation?

I am trying to rotate an object along the world axis while considering the direction of the camera, so that the rotation remains consistent even when the camera changes direction. The current code allows me to rotate a sphere along the world axis. However ...

Using Redux to add an object to an array nested within another array

Hey there! I'm facing an issue with creating, updating, or deleting {note} in the [notes] array based on the operationId in the parent array id. I've tried using ADDNOTE but it's not working as expected. The problem is that without these fun ...

Experiencing a 403 error when using Django with jQuery and Ajax

I am currently working on implementing ajax functionality, but I keep encountering a 403 error. My experience with jquery is still limited. Below is the code snippet that I have been using: $('#prod_search_button').click(function(){ if ...