AngularJS $resource GET params appear in URL - angularjs

My REST backend [ based on NodeJS/express/mongojs] is complaining 404 (not found) when Params are attached as part of URL. Backend rest interface is coded as below;
var express = require('express');
var router = express.Router();
router.get('/login', auth.signin); //auth.signin is code to verify user
Above REST service is consumed by AngularJS based frontend through $resource as below;
Definition:
angular.module('myapp').factory('signinmgr', function($resource) {
return $resource("http://localhost:3000/login", {}, {
'get': {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}});
Usage:
signinmgr.get({'username':'myname', 'password':'mypass'}, function(data){
//success
}, function(x){
//failed
});
Problem:
Frontend code above produces a URL to consume REST service where parameters are part of URL i.e. http://localhost:port/login?username=myname&password=mypass [if I use GET method, POST is OK]. I wanted my front end to keep URL as http://localhost:port/login and post any parameters through body as backend is using req.body.paramName to read those. [Actual Solution]
If (1) cannot be done, and my frontend is sending params as part of URL, I needed help as to know how to equip my backend to allow this URL with parameters so that backend doesnt return 404 as the base URL http://localhost:port/login is already there.
PS: for (1), I tried this thread with data:{username:'',password:''} but of no use. Please help if I am missing something very obvious or some concept.

Try the $http service instead:
angular.module('myapp').factor('signinmgr', function($http) {
return {
login: function (username, password) {
$http.post("http://localhost:3000/login", {
username: username,
password: password
}
}
};
});
signinmgr.login('myname', 'mypass').then(function(data){
//success
}, function(x){
//failed
});

Each request that my nodejs/expressjs backend receives has three places for passed attributes;
params{}
query{}
body{}
My problem (1) cannot be fixed in case I want to use GET method since with GET request parameters are visible as part of URL i.e. http://localhost:port/login?username=myname&password=mypass. To send my username/password I had to use POST that sends parameters as part of body{}.
My problem (2) was that I was using GET and mistakenly looking for parameters in body{} of request. Instead, parameters passed as part of URL in GET request are added to query{} of the request.

Related

Status Code 405 while using google oauth2

I am using Django with Angular JS to access the Google Drive API. I am following this document from Google. The FLOW.step1_get_authorize_url() gives me the URL similar to the sample URL mentioned on the page. But the problem is that after return HttpResponseRedirect(authorize_url) the browser does not redirect to the authorize_url and gives the error as shown in the picture below (Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 405).
But if I copy pasted the URL, it works fine.
The oauth2 function looks like this.
def index(request):
FLOW = flow_from_clientsecrets(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scope='https://www.googleapis.com/auth/drive',
redirect_uri='http://127.0.0.1:8000/oauth2callback/'
)
FLOW.params['access_type'] = 'offline'
authorize_url = FLOW.step1_get_authorize_url()
return HttpResponseRedirect(authorize_url)
And here is the oauth2callback function.
def auth_return(request):
credential = FLOW.step2_exchange(request.GET)
return HttpResponseRedirect("/mycustomurl")
I used this to enable CORS in the Django Server Side. Here is my part of service in Angular that makes the call to oauth2.
(function () {
'use strict';
angular.module('myApp')
.service('myService', function ($http) {
this.saveToDrive = function (startYear, endYear, shape) {
var config = {
params: {
start: '1999',
end: '2002',
action: 'download-to-drive'
},
headers: {
'Access-Control-Allow-Origin': '*',
'X-Requested-With': null
}
}
var promise = $http.get('/oauth2/', config)
.then(function (response) {
return response.data;
});
return promise;
};
});
})();
Please suggest what am I missing here. Any help or suggestions are highly appreciated.
I found it be a minor design issue rather than the code issue. I separated the logic that sends the oauth2 request to the client, and after the oauth2 request, I sent request to internal API with the params options. And now it's working fine.

how to use response.redirect in webapi+asp.net?

I want to redirect to another .aspx page from WebAPI. I have used this code but it is not working:
string url = "http://localhost:61884/UserList.aspx";
System.Uri uri = new System.Uri(url);
return Redirect(uri).ToString();
You don't. (or your description of the problem is not accurate)
Web API is meant to retrieve data or persist data, it is a way to interact with the server from the client without having to do the traditional form post or page request calls. The caller (javascript based on your question tag angularJs) needs to execute the redirect once the results from the call to the Web API are retrieved.
This is good SOC (separation of concerns), the business logic in the Web API should not care about routes (angularjs) / web pages.
Even if you wanted to the Web API, because of how its called, can't redirect the client.
Summary: The Web API code itself should not any type of redirecting of the client. The client should handle this.
Sample call to web api and redirect from angular code:
$http({
url: "/api/SomeWebApiUrl",
data: {},
method: "POST",
headers: { 'Content-Type': "application/json" },
responseType: "json"
}).then(function (response) {
if(response.data.somethingToCheck === someConditionThatWarrentsRedirect)
$window.location.href = "~/someOtherUrl/";
});
try something like this:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Hope that helps.
Redirect from asp.net web api post action
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}

web api 2 post with parameter - must use json.stringyfi

I'm using angularjs and I'm trying to make a HttpPost call to my web api.
My api method:
[HttpPost]
[Route("authentication/getkey")]
public IHttpActionResult GetKey([FromBody]string password) {
//Do stuff
}
my call:
service.getKey = function (password) {
return $http.post('api/authentication/getkey', JSON.stringify(password))
.then(function(result) {
return result.data;
});
}
Now this works fine, but do I really need to use JSON.stringify? I tried sending it like below, but all of them get password = null. Do I have to use JSON.stringify or am I doing it wrong in my other examples?
//Doesnt work
service.getKey = function (password) {
return $http.post('api/authentication/getkey', password)
.then(function(result) {
return result.data;
});
}
//Doesnt work
service.getKey = function (password) {
return $http.post('api/authentication/getkey', {password})
.then(function(result) {
return result.data;
});
}
If you don't want to use JSON.stringify, the other option will be to send the data as application/x-www-form-urlencoded as pointed in other answer as well. This way you are sending the data as form data. I'm not sure about the syntax of the $http.post Shortcut method but the idea is the same.
service.getKey = function (password) {
$http({
method: 'POST',
url: 'api/authentication/getkey',
data: $.param({ '': password }),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(result) {
return result.data;
});
From Microsoft's Web API official documentation about Parameter Binding in ASP.NET Web API:
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
Angular $http service sends Content-Type: application/json as header by default in POST requests, as you can see from the official docs, so Web API is trying to bind your request body using his JsonFormatter. Because of this you have to provide him a well formatted Json string (not a Json Object with a string inside) to correctly bind his raw string parameter.
As a side note, you could also send a request using application/x-www-form-urlencoded as Content-Type header, but then you will have to format your body as form parameters (using something similar to jQuery $.param( .. ))

AngularJS POST with $resource sending in query string, what am I doing wrong?

I'm a bit of a noob with Angular and am having issues trying to post to a Drupal Services endpoint. I can post just fine with HttpRequester (FFox plugin), however all my attempts with Angular to post data to get a session result in 401 Unauthorized: missing required argument username or other errors.
Here is my testing factory resource with default input:
userInfoApp.factory('LoginService', function($resource) {
return $resource('/auth-service/user/login', {username: 'admin', password: 'admin'}, {
update: {
method: 'POST', // this method issues a POST request
headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}
});
});
Here is the call I am making to it inside the controller (this):
this.login = function() {
var login = LoginService.update(function(data) {
console.log(data);
});
};
So far this usually results in a query string generated like so:
http://project.loc/auth-service/user/login?password=admin&username=admin
and the response of:
401 Unauthorized : Missing required argument username
What might I be doing wrong here? I have gotten $resource to work just fine with other endpoints (like for a menu service to retrieve a menu) however posting seems to be much more finicky. Any suggestions would be appreciated.
Thanks
Your current configuration for $resource sends username & password as querystring. Hence they appear in your URL. I assume you need these values to be POST.
According to documentations all non GET methods have a payload parameter in the action method:
non-GET "class" actions: Resource.action([parameters], postData,
[success], [error])
What you need to do is stop sending the parameters as default [parameters] and make use of the postData to POST data to your Drupal Services endpoint. You could do this when you call $update() as:
LoginService.update({}, {username: "admin",password: "admin"});
Ok, I found a way that works; for the controller function:
this.login = function() {
var data = {
username: this.username,
password: this.password
};
var login = LoginService.save({}, data,
function(data) {
// possibly do stuff with result
},
function(reply) {
// Comments on best way to access $scope here are welcome.
// This feels a bit weird to me.
$scope.info.errorMessage = reply.statusText;
}
);
};
And for the factory service:
// Login factory service
userInfoApp.factory('LoginService', function($resource) {
return $resource('/auth-service/user/login');
});
This actually retrieves the session id and other user data from the server.

Patch request with angular.js is send to wrong url

My REST API is configured to accept this kind of request
public function lockUserAction($slug)
{} // "lock_user" [PATCH] /users/{slug}/lock
So sending a patch request to
/api/users/2/lock
Will lock the user with id=2. This is my rest service inside angular.js
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id',
{},
{
list: { method: 'GET' },
lock: { method: 'PATCH' }
}
);
return User;
});
List works just finde, but lock does not work. The console prints:
PATCH /api/users 405 (Method Not Allowed)
I invoke it like this
$scope.lock = function(user){
user.$lock();
}
In the error message I see the url /api/users instead of /api/users/2/lock. Is this normal behaviour? Of course list excepts only GET requests and PATCH requests are not allowed on /api/users only on /api/users/{slug}/lock.
Any ideas why /api/users is called and not /api/users/{slug}/lock. Any ideas how to fix this?
When you call $lock angular has no idea that you intend to call the same url as before, with some extra path element. Also there is no way for angular to know what is a value of :id param.
Than let angular know about locking:
var User = $resource('/api/users/:id/:action', //add param to the url
{},
{
list: { method: 'GET' },
lock: { method: 'PATCH',params:{action:"lock",id:"#id"}} //set param value, so angular knows where to send request, #id refers to user id in json representation of user
}
);

Resources