What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data is available when checking the link by right-clicking. I'm unsure where I went wrong, so I would appreciate any help on this matter.

Here are the links for easy reference: https://i.sstatic.net/gVY3h.jpg Data Available at this location https://i.sstatic.net/yu9Bj.jpg

file.json   
    [    
        {"name":"English","value":true},
        {"name":"Spanish","value":false},
        {"name":"German", "value":false},
        {"name":"Russian","value":false},
        {"name":"Korean", "value":false}
    ]

// Code implementation

var app = angular.module('myApp', []);


app.service('JSONService', function($http){         
    return{
        getJSON: function(){
            return $http.get('file.json')
                .then(function(response){
                    return response.data;
                });
        }
    };
 });

app.controller('myCtrl',['$scope', 'JSONService','$http', function( $scope, JSONService, $http) {
  JSONService.getJSON().then(function(data){
       $scope.languages = data;
  });

//inputting json directly for this example
// $scope.languages = [        
//    {name:"English", value:true},
//    {name:"Spanish", value:false},
//    {name:"German", value:false},
//    {name:"Russian", value:false},
//    {name:"Korean", value:false}
//  ];

  $scope.save = function() {
 //   $http.post('file.json', $scope.languages).then(function(data) {
 //     $scope.msg = 'Data saved';
 //   });
    
$http({                
    url: 'file.json',
    method: "POST",
    data:$scope.languages,
    headers: {
        'Content-Type': 'application/json', 
        'Accept': 'application/json' 
    }
});

  };
}]);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="script.js"></script>
  </head>

  
<body ng-app="myApp" ng-controller="myCtrl">
  <form>
    <div ng-repeat="lang in languages">// Displaying checkboxes for each language
      <label>{{lang.name}}</label>
      <input type="checkbox" min="0" max="4" ng-model="lang.value" >
    </div>
    <button ng-click="save()">Save</button> // Save button triggers save function
    <p>{{msg}}</p> // Message displayed after saving data
</form>
</body>

</html>

Answer №1

Give this method a try:

$http.post(site_url+'management/createUser/',{
                        'firstName'     : user.firstName,
                        'email'         : user.email,
                        'password'      : user.password
                     }).then(function (response) {
                             //handle success
                     })
                     .catch(function (error) {
                            //handle error
                     });

Answer №2

When accessing a .json file without using a server, it is important to only use the GET method. By default, files are retrieved using HTTP GET method.

Because the JSON file is not served through a Server or server-side code, it does not support other HTTP methods like POST or DELETE, only GET.

If you intend to save post data to a .json file, this cannot be accomplished with $HTTP alone. You will need server-side handling for this task.

Answer №3

It's important to note that when it comes to interacting with files, the browser can only perform a `GET` request on resources like file.json since it can access known file locations. However, browsers do not have the capability to directly write to files, except in cases where Chrome uses specific sandboxing features through the file API. For any other writing operations, a backend server is required to handle and process the data sent via a `POST` request.

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

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

Manage the angularJS user interface switch through an external event

I have implemented an AngularJS Material UI switch and I am looking to update its status based on an external event. This event occurs when a MQTT message is received on a specific topic that is published. To achieve this, I am utilizing a Node.js MQTT cli ...

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

Use .empty() method to remove all contents from the tbody element after creating a table

Currently, I am working on a project where I am creating a drop-down list to assist users in selecting media and ink for their printers. The goal is to then generate a table displaying the selected results. While I have managed to successfully generate the ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

When working with JavaScript, the `textarea` value property will not recognize line breaks or white spaces when being read

Recently, I've been developing a browser-based notebook app. However, I encountered an issue where if I type a note like this: *hello this is my first note The app displays it as: hello this is my first note Additionally, I want elements with the ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

utilizing various ajax functions

I'm having trouble using additional functions with the "complete:" option in JQuery ajax after the "selectOptionSort" function. Can anyone help me figure out what's wrong? $('#tipos').change(function(){ $("#marcas ...

Utilizing AngularJS to dynamically inject HTML content into $scope

In my possession are the following files: index.html //includes instructions for passing arguments to the btnClick function in app.js <div ng-bind-html="currentDisplay"></div> app.js app.factory('oneFac', function ($http){ var htm ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...

Reducer is not a standalone function in the realm of React Native's Redux framework

I need to implement a reducer in my react native application. The store constant is defined as follows: export const USER_PROFILE = 'USER_PROFILE'; This is the content of action.js file: import {USER_PROFILE} from '../constants/index'; ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

Developing a Mongoose organization/class framework?

Currently, I'm in the process of developing a web application using Node.js, Express, and Mongoose/MongoDB. An important query has arisen regarding how to effectively organize and structure methods related to Mongoose. It's necessary for me to u ...

Why is the UI Router controller failing to function properly after loading the view from the $templateCache?

I've been utilizing gulp-angular-templatecache to convert my filename.view.html files into a consolidated templates.js file. Afterwards, I use $stateProvider to define states and fetch the templates from $templateCache, including an abstract "root" s ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

Save JSON Tree data in the Database

Given a tree structure JSON, I am tasked with creating an API to insert all the data into a database at once. The organization entities can have multiple parents and children relationships. An example of the JSON data: { "org_name": "orga ...