Afroza Yasmin
Afroza Yasmin

Reputation: 511

AngularJs $http.post request using JSON

I want to create a post request using JSON file. It's working for $http.get request but don't work for $http.post. My method for a get request is -

$http.get('data/data1.json').success(function(res){
    $scope.myDataSet = res;     
})

& It's returning all the JSON data that I saved in Json file. Now I want to create a post request that saved the data in this Json file, The method that I used for this -

var obj = {
            Id: $scope.id,
            Name: $scope.name
        }

        $http({
            url: 'data/data1.json',
            dataType: 'json',
            method: 'POST',
            data: obj,
            headers: {
                "Content-Type": "application/json"
            }
        }).success(function(response){
            $scope.myDataSet = response;
        }).error(function(error){
            $scope.error = error;
        });

& the error shows in browser - POST http://localhost:3000/data/data1.json 404 (Not Found).

Remote Address:[::1]:3000
Request URL:http://localhost:3000/data/data1.json
Request Method:POST
Status Code:404 Not Found
Response Headers
view source
Connection:keep-alive
Content-Length:29
Content-Type:text/html; charset=utf-8
Date:Sat, 21 Nov 2015 06:10:47 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:13
Content-Type:application/json
Cookie:connect.sid=s%3ALlxaAOKSIGfyAfJIkxrRqDp2yDR4mqmd.%2BY9r%2FcOUStykG4ut5yvleAK6PHZ5KqvHCOjUUY%2BmS%2Fs; _ga=GA1.1.242893980.1444535433
DNT:1
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

How can I saved the object data in this Json file..Please help me.

Upvotes: 1

Views: 1363

Answers (1)

Chandan
Chandan

Reputation: 1138

If you are not using server and directly calling the .json file then it should only be called as GET method. All the files are retrieved by default using HTTP GET method.

Since it is a pure JSON file and is not served through Server or any server side code, it won't be able to handle other HTTP methods such as POST, DELETE etc other than GET.

UPDATE -

In your comment, you mentioned you want to save this post data to .json file. If this is your intention then this can not be done using $HTTP, you will need to handle this on server side.

Upvotes: 1

Related Questions