Cross Origin call is not allowing in browser - angularjs

I am trying to call one application to another where I am getting and error as "Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response." and in my back-end I have used the following code as mentioned below
List<String> originList = Arrays.asList(origins.trim().split("( )*,( )*"));
String origin = request.getHeader("Origin");
if (originList.contains(origin)) {
originAllow = origin;
} else {
originAllow = originList.get(0);
}
response.setHeader("Access-Control-Allow-Origin", originAllow);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, accept, authorization");
response.setHeader("Access-Control-Expose-Headers", "Location");
In originAllow I am passing the url which I am trying to access but I am getting the below error,
XMLHttpRequest cannot load http://<<url>>. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Please find the browser request and response header,
Response Header
Access-Control-Allow-Headers:x-requested-with, content-type
Access-Control-Allow-Methods:GET OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Connection:close
Content-Length:0
Content-Type:text/plain; charset=UTF-8
Server:Apache-Coyote/1.1
X-Application-Context::8080
Request Header
Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ms;q=0.6
Access-Control-Request-Headers:authorization, x-requested-with
Access-Control-Request-Method:GET
Connection:keep-alive
Host:myrestapi-dev
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
OPTIONS <>?page=0&search_param=test&size=10,desc HTTP/1.1
Host: myrestapi-dev
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:9000
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Access-Control-Request-Headers: authorization, x-requested-with
Accept: /
Referer: http://localhost:9000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ms;q=0.6
I am running application in localhost:port and the other application is using deployed url where the protocol,host are different.
Please let me know Is there anything I need to add to access the url from ui(angular) for authorization moreover it is working in other browser but not in chrome

this is because your server isn't allowing the authorization header.
To address it:
response.setHeader("Access-Control-Allow-Headers", "Content-Type, authorization");
should help you. as I am not sure about your backend I need to explain a bit more.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type request header).Moreover, You need to make AJAX call from the same domain or make server-side changes, allowing requests from external domains.To address this you need to make changes in headers at http://yourdomain.com by allowing your external domain in headers:
Access-Control-Allow-Origin: *
1- ref1
2- ref2
Possible solution in AngularJs. : Using JSONP with Angular
The AngularJS $http service has a built-in method called "jsonp".
var url = "some REST API Url" + "?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
// whatever
});
Also, the url had to be appended with ?callback=JSON_CALLBACK.
I am going to expand this solution using JSONP
exampleurl = 'http://wikidata.org/w/api.php?whatever....&format=json'
//Number 1 :
$.ajax({
dataType: "jsonp",
url: exampleurl ,
}).done(function ( data ) {
// do whatever
});
//Number 2 :
$.ajax({
dataType: "json",
url: exampleurl + '&callback=?',
}).done(function ( data ) {
// do whatever
});
//Number 3 :
$.getJSON( exampleurl + '&callback=?', function(data) {
// do whatever
});
more information
1- getJson
2-$.Ajax

Related

$http.post() method is actally sending a GET

NOTE:
I've found a possibly related issue that warrants a new question here
This is a weird problem. I've been using angular over the course of 2 years and have never run into this problem.
I'm using angular v1.5.0. I'm making a post request like this:
$http({
method: "POST",
url: "/myurl",
data: {
file: myFile // This is just an object
}
});
Run-of-the-mill POST request right? Get this. I look in the console and the Network tab logs the request as a GET. Bizarre. So I've jiggered the code to work like this:
$http.post("/myurl", {file: myFile});
Same thing. After stepping through the $http service code I'm confident that the headers are being set properly. Has anyone else run into this problem?
Update
Taking germanio's advice, i've tried using the $resource service instead:
promise = $resource("/upload").save()
(this returns an error for another reason, it still executes the POST properly). I'm having the same problem: the request is logged as a GET in the console.
Here are the headers of the request when it gets to my server:
GET /myurl/ HTTP/1.1
Host: localhost:8001
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Pragma: no-cache
Referer: http://localhost:8001/myurl/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Update 2
As per georgeawg's suggestion I've used an interceptor to log the request at its various stages. Here is the interceptor code:
$httpProvider.interceptors.push(function() {
return {
request: function(config) {
console.log(config);
return config;
}
}
}
Having run this code I get this logged:
data:Object // contains file object
headers: Object // has Content-Type set to multipart
method:"POST" // ???
url :"/myurl
So this means the request is being sent as a POST from within Angular, but it is still logged as a GET both in the browser and on my server. I think there is something low level at work here about the HTTP protocol that I dont understand.
Is the request sent to the server before it is actually logged in the browser? If so, that might atleast point to my server as the culprit.
In the hopes of finding out whats going on, here is my server code:
type FormStruct struct {
Test string
}
func PHandler(w http.ResponseWriter, r *http.Request) {
var t FormStruct
req, _ := httputil.DumpRequest(r, true)
log.Println(string(req))
log.Println(r.Method) // GET
log.Println(r.Body)
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&t)
log.Println("Decoding complete")
if err != nil {
log.Println("Error")
panic(err.Error()+"\n\n")
}
log.Println(t.Test)
w.Write([]byte("Upload complete, no errors"))
}
func main() {
http.HandleFunc("/myurl/", PHandler)
fmt.Println("Go Server listening on port 8001")
http.ListenAndServe(":8001", nil)
}
My server throws an EOF error when it receives the request:
2016/03/30 10:51:37 http: panic serving [::1]:52039: EOF
Not sure what an EOF would even mean in this context.
Update 3
By the suggestion of another use, I tried using POSTMAN to hit my server with a fake POST request. The server receives the request properly. This means to me that there is something up with how angular is making the POST request. Please help.
Any ideas?
Full server logs:
Go Server listening on port 8001
2016/03/30 11:13:08 GET /myurl/ HTTP/1.1
Host: localhost:8001
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Postman-Token: 33d3de90-907e-4350-c703-6c57a4ce4ac0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
X-Xsrf-Token: null
2016/03/30 11:13:08 GET
2016/03/30 11:13:08 {}
2016/03/30 11:13:08 Decoding complete
2016/03/30 11:13:08 Error
2016/03/30 11:13:08 http: panic serving [::1]:52228: EOF
goroutine 5 [running]:
net/http.(*conn).serve.func1(0xc820016180)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1389 +0xc1
panic(0x3168c0, 0xc82000b1a0)
/usr/local/Cellar/go/1.6/libexec/src/runtime/panic.go:426 +0x4e9
routes.FUPHandler(0x1055870, 0xc820061ee0, 0xc820104000)
/Users/projectpath/routes.go:42 +0x695
net/http.HandlerFunc.ServeHTTP(0x4e7e20, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1618 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc820014b40, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1910 +0x17d
net/http.serverHandler.ServeHTTP(0xc820016100, 0x1055870, 0xc820061ee0, 0xc820104000)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc820016180)
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
/usr/local/Cellar/go/1.6/libexec/src/net/http/server.go:2137 +0x44e
Update 4
I stumbled onto something interesting:
Charles logs a POST request when I post to myurl, but the response status is 301. After the POST a GET is logged. This is the GET that is hitting my server.
My server, as you can see above, does not do any sort of redirection. How is the 301 happening?
This is due to a security consideration.
In your situation when a redirect is sent back from the server to the browser, the browser will not repeat the POST request (but rather just a "simple" GET request).
Generally speaking a browser will not send POST data to a redirect URL because the browser is not qualified to decide if you're willing to send the same data to the new URL what you intended to send to the original URL (think about passwords, credit card numbers and other sensitive data). But don't try to circumvent it, simply use registered path of your handler to POST to, or any of the other tips mentioned in the linked answer.
For context see question:
Go web server is automatically redirecting POST requests
You can read more on the subject here:
Why doesn't HTTP have POST redirect?
This code actually send GET to server
$http({
method: 'POST',
params: {
LoginForm_Login: userData.username,
LoginForm_Password: userData.password
},
url: YOURURL
}).then(
You need to use transformRequest, sample below actually send POST
$http({
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
LoginForm_Login: userData.username,
LoginForm_Password: userData.password
},
url: YOURURL
}).then(

CORS issue with angular $http.post - successful requests result in errors with status 0

I'm using angular to POST to an authentication endpoint; on the server side, I can see the request succeed, and proper CORS headers are set. Angular's origin is http://localhost:9000
On the server side, preflight OPTIONS requests always get a 200 back, so that seems OK.
On the client side, the $http.post always fails with an error code of 0, which from other research suggests something is still wrong with CORS. I've read the spec and tried a number of other answers, yet something is still missing.
Angular POSTs like this:
$http({
method: 'POST',
url: 'http://localhost:3000/auth/login',
data: {
username: $scope.username,
password: $scope.password
}
})
.then(function (response) {
/* etc. etc. */
}, function (response) {
/* This always triggers, with response.status = 0 */
console.log("ERROR: " + response.data);
console.log("Status: " + response.status);
console.log("Status text: " + response.statusText);
console.log("Headers: " + response.headers);
$scope.error = 'Something went wrong...';
});
Using curl to debug what the server is sending back, this is it:
< HTTP/1.1 302 Found
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
< Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, Content-Length, X-Requested-With
< Access-Control-Allow-Credentials: true
< Set-Cookie: ua_session_token=(blahblah); Path=/
< Location: /
< Vary: Accept
< Content-Type: text/plain; charset=utf-8
< Content-Length: 23
< Date: Mon, 28 Dec 2015 15:08:17 GMT
< Connection: keep-alive
This is why I'm at a loss, as per the specification, the server seems to be doing the right thing?
Here's what the server gets from the client in terms of request headers:
HEADER host localhost:3000
HEADER content-type application/json;charset=UTF-8
HEADER origin http://localhost:9000
HEADER content-length 38
HEADER connection keep-alive
HEADER accept application/json, text/plain, */*
HEADER user-agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9
HEADER referer http://localhost:9000/
HEADER accept-language en-us
HEADER accept-encoding gzip, deflate
UPDATE tried something else with no luck, based on this post. It would seem Access-Control-Allow-Headers is case-sensitive, and angular is sending on the request accept, origin, content-type. I tweaked the server to parrot back the same, with no luck.
Alright, after applying my head to my keyboard for several hours, I've fixed it.
The answer seems to be that angular really doesn't like getting redirects in response to POST. When I changed the server endpoint to return just a plain auth token as text (the same token it was setting as a cookie anyway) rather than returning a redirect, the angular POST started working like a charm and falling through to the success handler.
Not sure I got deep enough into this to know why angular was behaving in that way; by playing around with it I found that if the redirect the server sent was to a nonexistent (404) URL that this could be replicated, EVEN IF the original POST returned that valid redirect.

Angular CORS requests fail to Laravel backend, but preflight look good

In short, I'm posting data with Angular to a Laravel backend. The OPTIONS/preflight request looks good, but the subsequent POST fails saying that Access-Control-Allow-Origin header is missing from the requested resource.
I'm using Laravel 5 with Angular 1.2.26. Some further documentation on the backend middleware can be found here: https://laracasts.com/discuss/channels/requests/laravel-5-cors-headers-with-filters.
Laravel middleware:
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin' , 'http://laravel.app:8001')
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With')
->header('Access-Control-Max-Age', '28800');
}
Angular config - I've tried with various combinations of the commented code, same results each time:
$httpProvider.defaults.useXDomain = true;
//$httpProvider.defaults.withCredentials = true;
//delete $httpProvider.defaults.headers.common["X-Requested-With"];
//$httpProvider.defaults.headers.common["Accept"] = "application/json";
//$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
Preflight/OPTIONS:
Remote Address:127.0.0.1:8000
Request URL:http://laravel.app:8000/api/v1/authentication/login
Request Method:OPTIONS
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:laravel.app:8000
Origin:http://laravel.app:8001
Referer:http://laravel.app:8001/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, Authorization, X-Requested-With
Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:http://laravel.app:8001
Access-Control-Max-Age:28800
Allow:GET,HEAD,POST
Cache-Control:no-cache
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Mon, 24 Nov 2014 16:01:57 GMT
Server:nginx/1.6.2
Set-Cookie:laravel_session=blahblah; expires=Mon, 24-Nov-2014 18:01:57 GMT; Max-Age=7200; path=/; httponly
Set-Cookie:XSRF-TOKEN=blahblah; expires=Thu, 01-Jan-1970 00:02:00 GMT; Max-Age=-1416844797; path=/; httponly
Transfer-Encoding:chunked
POST:
Remote Address:127.0.0.1:8000
Request URL:http://laravel.app:8000/api/v1/authentication/login
Request Method:POST
Status Code:500 Internal Server Error
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:47
Content-Type:application/json;charset=UTF-8
Host:laravel.app:8000
Origin:http://laravel.app:8001
Referer:http://laravel.app:8001/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36
Request Payload
{email: "x", password: "x", rememberMe: false}
email: "x"
password: "x"
rememberMe: false
Response Headers
Cache-Control:no-cache
Connection:keep-alive
Content-Type:text/html; charset=UTF-8
Date:Mon, 24 Nov 2014 16:01:57 GMT
Server:nginx/1.6.2
Transfer-Encoding:chunked
After stepping through the VerifyCsrfToken middleware I've established that it was indeed a token mismatch.
The reason is that Angular was not supplying the CSRF token via header or via a parameter in the post. It worked for GET and OPTIONS requests because these do not validate against the token.
So, I looked into Angular and there is documentation on XSRF Protection (see https://docs.angularjs.org/api/ng/service/$http) and lots of discussion out there on how to add the appropriate headers (e.g. https://github.com/angular/angular.js/issues/5122#issuecomment-36157820).
I haven't had a chance to follow any of this up as I have to keep my project moving and my particular use case allows me to get away with disabling VerifyCsrfToken as I only need CORS whilst in development.
But hopefully this will give someone else a starting point for solving this issue more fully.
I am unsure if this is an issue with Laravel and the VerifyCsrfToken middleware or not, but the root cause of my issue was that the CSRF token validation was failing. When the error was thrown, the new headers were not included. I'm unclear on the order that these middlewares run in, perhaps that's it, but nonetheless, once I removed the VerifyCsrfToken from the middleware stack, everything lit up.
I had seme problem. If you use middleware to set Headers, but create a new Response, Response::json(), Response::make(), etc. on controller, this new object don't get the headers set by middleware.
I had same problem.
In CORS middleware
Add the following header.
public function handle($request, Closure $next)
{
//All the domains you want to whitelist
$trusted_domains = ["http://localhost:4200", "http://127.0.0.1:4200", "http://localhost:3000", "http://127.0.0.1:3000"];
if (isset($request->server()['HTTP_ORIGIN'])) {
$origin = $request->server()['HTTP_ORIGIN'];
if (in_array($origin, $trusted_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token,x-xsrf-token');
header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
}
}
return $next($request);
}

OPTIONS Error using Ionic AngularJS $http PUT, POST or DELETE requests

I know this has been asked time and time again but I cannot seem to fix my issue no matter what solution I try.
I'm trying to create a new user using AngularJS within Ionic. I have set up a small REST server on my localhost along with my testing of the app. So they are on the same server but are just in different folders. Nevertheless, I still need to apply CORS for some reason...
Using the $http method in AngularJS in a service I can do GET requests. However, when I try a PUT, POST or DELETE request I get an OPTIONS error in the console. Below are the settings I have...
API index.php File
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
My UsersSvc
app.factory('UsersSvc', function($http, $location){
return {
/**
* Adds a user to the database
*
* #param user
* #returns {*}
*/
addUser: function(user){
// User Format...
// user.user_email, user.user_password
return $http.post($location.apiUrl + '/credentials/add_user',
{user: user}).
success(function(data){return data});
}
};
});
Rest Server API method (I am using CodeIgniter and using Phil Sturgeon's REST server)
class Credentials extends REST_Controller {
public function add_user_post(){
$user = $this->user_model->add_user($this->post('user'));
if($user){
$this->response($user, 200);
}
else{
$this->response(
ENVIRONMENT == 'development' ? $this->db->last_query(): null,
ENVIRONMENT == 'development' ? 404 : 204
);
}
}
}
The Error in the Chrome Console
OPTIONS http://localhost/z-projects/git-motostatsfree/MotoStats/MotoStatsAPI/credentials/add_user
(index):1 XMLHttpRequest cannot load http://localhost/z-projects/git-motostatsfree/MotoStats/MotoStatsAPI/credentials/add_user. Invalid HTTP status code 404
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,en-GB;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost
Origin:http://localhost:8100
Pragma:no-cache
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36
Response Headers
Access-Control-Allow-Headers:Origin, X-Requested-With, content-type, accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Connection:Keep-Alive
Content-Length:42
Content-Type:application/json; charset=utf-8
Date:Thu, 20 Nov 2014 23:04:35 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.7 (Unix) PHP/5.5.9 OpenSSL/1.0.1f mod_perl/2.0.8-dev Perl/v5.16.3
Set-Cookie:ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22326db0454f2f256da6b6a526ed62cd2d%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A3%3A%22%3A%3A1%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A120%3A%22Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_10_1%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F39.0.2171.65+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1416524675%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D3a3dfab89040b0df83c80eef434d063f; expires=Fri, 21-Nov-2014 01:04:35 GMT; Max-Age=7200; path=/
X-Powered-By:PHP/5.5.9
Any solution or a nudge in the right direction would be a massive help. I've been working on this for 4 hours already and still cannot figure it out.

AngularJS $resource DELETE item in collection

I have an ASP.NET Web Api (1) controller with GET, POST and DELETE actions. I am calling this from an Angular 1.2.0 RC3 app with $resource. Let's call the controller Foos.
I do a GET that returns a list of foos:
GET http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
where the resource is
/api/foos/clientId/recordId
Here I am saying get me a list of foos for client x and record y
Now, I want to remove a single foo from the list of foos that I received, so I call $delete:
$scope.delete = function(foo){
foo.$delete();
}
however this results in the following request:
DELETE http://localhost:55386/api/foos/123456/1 HTTP/1.1
Host: localhost:55386
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
This delete is obviously trying to delete the entire list of foos, which makes sence.
My question is, how do I delete a single foo using Angular's $resource without getting each foo in its own GET request?
UPDATE:
I could do a GET /api/foo/1 where the resource is foo/fooId, and its equivalent DELETE /api/foo/1 to delete it but I want to get a list of foos instead of each foo individually.
I know that is not the question but you should restangular https://github.com/mgonto/restangular. It is easier to interact with rest services
I was misunderstanding how $resource works. I assumed thatfoo knew how to delete itself as it is a Resource 'instance' in the following function:
$scope.delete = function(foo){
foo.$delete();
}
The correct approach is:
$scope.delete = function(foo){
Api.delete({
id: foo.Id,
clientId : $scope.clientId,
recordId : $scope.recordId
});
}
You have to manually tell the $resource instance to use the id of foo so that the url includes the foo id and does the following DELETE
DELETE http://localhost:55386/api/foos/123456/1/123 HTTP/1.1
where 123 is fooId

Resources