Post Data to WebApi from AngularJS - angularjs

i want to Post a User to WebApi
Ive written this Controller :
public class AccountController : ApiController
{
public UserModel Get([FromUri]string username, [FromUri]string password)
{
var repository = new MongoRepository<User>();
User result = repository.Single(x => x.Username == username && x.Password == password);
UserModel user = result.ToUserModel();
if (result != null)
{
result.LastLogin = DateTime.Now;
user.LastLogin = DateTime.Now;
repository.Update(result);
}
return user;
}
public GenericResultModel Post(User user)
{
var repository = new MongoRepository<User>();
var existingUser = repository.Single(x => x.Username == user.Username || x.EmailAdress == user.EmailAdress);
if (existingUser == null)
{
if (repository.Add(user) != null)
{
return new GenericResultModel{Success = true, Errors = new List<string>()};
}
return new GenericResultModel(){Success = false, Errors = new List<string>(){"There was an Error adding the User !"}};
}
return new GenericResultModel(){Errors = new List<string>(){"The User already exists !"}, Success = false};
}
}
My RouteConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
And my AngularJS Controller
mod.controller('accountCtrl', function ($scope, $http, $window, $location) {
$scope.credentials = { username: '', password: '' };
$scope.Login = function () {
$http({
method: 'GET',
url: 'http://localhost:9239/Api/Account/Get?username=' + $scope.credentials.username + '&password=' + $scope.credentials.password,
/* data: JSON.stringify(credentials), */
headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json' }
}).
success(function (data, status, headers, config) {
$window.sessionStorage.setItem('loginToken', data.Id);
//$location.redirectTo('/Home');
}).
error(function (data, status) {
console.log("Request Failed");
});
};
$scope.registerModel = { username: '', password: '', passwordrepeat: '', email: '', emailrepeat: '' };
$scope.RegisterUser = function () {
$http.post('http://localhost:9239/Account/',$scope.registerModel);
};
});
When i login, everythign works fine.
But when i post a new User i get a 404 Not Found Error.
I tryied the [FromBody] Attribute but it didnt worked
When i debug my Code wont hit by the Service ...
Any Ideas ?

Assuming you didn't make any typos in the api url you POST to, the problem is not in your angular code.
HTTP 404 Not Found
The 404 or Not Found error message is a HTTP standard response code indicating
that the client was able to communicate with the server,
but the server could not find what was requested.
If you had tried to POST a user to http://localhost:9239/Account using, for example, the program curl, you would also have gotten this 404 code.
If you had opened your browser and surfed to http://localhost:9239/Account you would also have gotten this 404 code.
Basically what it means is that the url you are trying to POST to doesn't 'exist'. I've been in this situation myself because I simply typo'd the url. The only other explanation I can think of is that the server is running fine, but there is no implementation for /Account, e.g. calls to that url aren't handled.

Related

getting undefined while sending http post method

I am Passing my user information http angularjs. backend code is PHP
As I am the beginner I am searching lot for this Issue. and tried a lot methods since 2 days but I couldn't find the reason, and how to fix it?. it may be simple but I couldn't find.
1.I am posting my http post request in angularJS I have been debugged the value which I will send is
Debugging value are as follow:
serializedParams:"send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
url: "insert.php?send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
result: undefined
I think the url is correct. but the result is undefined
var app = angular.module("myapp", []);
app.controller("booking", function($scope, $http) {
$scope.paidops = ["Paid", "Due"];
$scope.value = "ADD";
$scope.insertvalues = function() {
alert($scope.id + ' , ' +
$scope.name + ' ,' + $scope.phone +
' , ' + $scope.status);
alert($scope.name);
var Indata = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
method: 'POST',
url: 'insert.php',
params: Indata,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
alert(JSON.stringify(response));
}, function(response) {
alert(response);
});
}
});
In PHP I am getting data like this way:
$connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking");
if($connect === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"),true);
if(count(array($data)) > 0)
{
$id_received = mysqli_real_escape_string($connect, $data->send_id);
$name_received = mysqli_real_escape_string($connect, $data->send_name);
$phone_received = mysqli_real_escape_string($connect, $data->send_phone);
$status_received = mysqli_real_escape_string($connect, $data->send_status);
$btnname_received = mysqli_real_escape_string($connect, $data->send_btnName);
if($btnname_received == 'ADD'){
$query = "INSERT INTO society_tour(id,name, phone, status) VALUES ('$id_received','$name_received', '$phone_received','$status_received')";
if(mysqli_query($connect, $query))
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
}
?>
Not entirely sure about the PHP part, but as you have json_decode in PHP, its safe to assume that PHP expects a JSON content-type
If so, here is how to post data to a url
var postUrl = 'insert.php'; // please check whether the url is correct
var dto = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
url: postUrl,
method: 'POST',
data: dto,
headers: {
"Content-Type": "application/json"
}
})
//...

Angularjs Post method can not get the parameter in Spring MVC

I'm trying to use Angularjs to send a Post request to My Spring Mvc Controller to login User.But I can't get the Parameter from the request.
this is my Angular js code:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
and this is the Spring MVC Controller code:
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(Model model,User user, HttpSession session, HttpServletRequest request) {
String phone = request.getParameter("phone");
String password = request.getParameter("password");
System.out.println(phone+","+password);
System.out.println(user.getPhone()+","+user.getPassword());
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser",u.getUser());
return u;
}
I have searched many resource,they said I should change the header and I have set the header:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
return true;
}
Actually,I can't request the login url,but after I setHeader,I can request the url,but the parameter is null.
Forgive my poor English, I am newbie in StackOverFlow.
I didn't konw is it have the same question in here ,but I can find the same question. Thank you for your view.
There are two points to fix. At first, data should be converted to a URL-encoded string. You can convert data object with $.param() method or set params property instad of data so it will look like this:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
The second point is server-side controller method. Here you have to annotate method's arguments appropriately. Consider using #RequestParam annotation.
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(
#RequestParam String phone,
#RequestParam String password,
HttpSession session,
HttpServletRequest request
) {
System.out.println(phone + ", " + password);
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser", u.getUser());
return u;
}
<!--In your script-->
var app = angular.module("myApp", [])
.controller("myController", function($http){
var vm= this;
Posting = function(name)
{
var data = 'name=' + name;
var url="example.htm";
$http.post(url, data).then(function (response) {
vm.msg = response.data;
alert(vm.msg);
});
}
});
// Above is same as using GET, but here below is important
//Dont forget to add this config ortherwise http bad request 400 error
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
}]);
//In spring controller same as of GET Method
#RequestMapping(value="example.htm", method = RequestMethod.POST)
#ModelAttribute("msg")
public String doingPost(#RequestParam(value="name") String name){
System.out.println(name);
return "successfully Posted";
}

Model passed to Web Api 2 method is null - AngualrJs

I'm calling a method inside my Web Api 2 controller, passing in a model called login which consists of EmailAddress and Password. However it hits the method but the model passed in is always null...
My call from AngularJs function :
var login = { "EmailAddress": emailAddress, "Password": password };
$http.post("/api/Login/", { headers: { 'RequestVerificationToken': $scope.antiForgeryToken } }, login).success(function () {
alert('succes');
}).error(function () {
alert('Unable to login at present, please try again later');
});
My method:
[ValidateAntiForgeryToken]
public void Post([FromBody]Login login)
{
var t = login.EmailAddress;
}
I think its something to do with how I've structure my actual Angular $http.post method but again I'm not sure, can anyone suggest would could potentially be wrong with it?
Can you use ajax and Razor?
var login = { "EmailAddress": emailAddress, "Password": password };
$.ajax({
url: "#Url.Action("api/login", "Controller", login)",
type: "GET",
data: {},
success: fCheckBoxes
});
Why cannot add the token to every request by configuring your app.js
// Set header for every request
app.factory('httpRequestInterceptor', function ($localStorage) {
return {
request: function (config) {
if ($localStorage.token != null)
config.headers['myAppToken'] = $localStorage.token;
return config;
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});

Not able to get AngularJs fileData from HttpServletRequest at server side

AngularJS Client Side:
userTab.factory('someService', ['apiService','$rootScope', function(apiService, $rootScope){
return {
updateData : function (someObj){
return apiService.request({
apiMethod: 'user/v1/updateData',
httpMethod: 'POST',
fileData: JSON.stringify(someObj)
}).error(function(data, status) {
throw "updateData error: " + status;
});
}
}
}]);
Server Side Code:
Update.java
#Controller("user")
#RequestMapping(value = "/user/v1")
public interface Update
{
#ResponseBody
#ResponseStatus(HttpStatus.CREATED)
#RequestMapping(value = "/users/{username}/updateData", method = POST)
String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username, #RequestBody UserUpdate userUpdate);
}
UpdateImpl.java
#Override
#Transactional
public String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username,
#RequestBody UserUpdate userUpdate) {
String requestBody = ServletUtils.getRequestBody(request);
logger.info("RequestBody: "+requestBody);
return new String("true");
}
Response:
RequestBody: {}
So as you see that RequestBody is coming as blank as I haven't given anything in params within angularjs API call.
So how to get the fileData which is not in params here?
UPDATE:
My fileData is a normal json array just like this:
{
"todo" : "Dinner",
"user" : [
{
"name" : "username",
"password" : "passwordabc"
}
],
"notes : "some notes"
}
And I have created it in an angularjs as follows:
var object = {};
object.todo = "Dinner";
object.notes = "some notes";
userArray = [{
name: 'myname',
password: 'password'
}];
object.user = userArray
UPDATE:
apiService.js
'use strict';
apiModule.factory('apiService', ['$http', '$q', 'LoginService','XSSValidator', function($http, $q, loginService, XSSValidator) {
var basePath="https://somesite.com/userApi/";
var _httpMethod="POST";
var caching=false;
var latestRequest={};
$http.defaults.withCredentials = true;
return{
if(typeof bundle.fileData != "undefined"){
return $http({
cache: caching,
method: bundle.httpMethod,
headers:{"Content-Type":contentType},
url:basePath+bundle.apiMethod,
data:dataStr,
transformRequest: angular.identity,
transformResponse:bundle.transformResponse,
timeout: canceller.promise
}).success(function(data, status, headers, config) {
//check to see if request has been redirected to login page, suggesting user has been logged out
if(typeof data==='string' && data.substr(0,44)==='<html><head><title>Login Page</title></head>'){
window.location.href="/login" + window.location.search;
}
var req;
if(config.data !== ""){
var requestArr=config.url.split(config.data);
req=requestArr[0].split("?")[0];
}
else{
req=config.url;
}
if(config.data !== "" && !data.fault){
if(Object.prototype.toString.call(data) == "[object String]"){
var msg = XSSValidator.validate("Response ", data);
if (msg != null) {
return $q.reject({ message: msg });
}
}else if(config.headers["Content-Type"] == "application/x-www-form-urlencoded" || config.headers["Content-Type"] == "application/json"){
eval(data);
}
}
if(latestRequest[req]!==config.url){
//cancel promise
return $q.reject({ message: 'Rejecting this promise' });
}
}).error(function(data, status, headers, config) {
if(status===401){ //user has been logged out server-side. redirect to login pg
window.location.href="/login" + window.location.search;
}
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}

angular.js http post to MVC async Task<ActionResult> web method fails

I Am trying to call an Async method in MVC controller (example Login) from an angular client and calls fail. I tried it with google postman tool also.
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
and here is the snippet of the angular service that is calling the Login method
var loginUser = function (email, password, returnUrl) {
var req = {
method: 'post',
url: '/Mysite/Login',
headers: {
'Content-Yype': undefined
},
data: {
model: {
Email: email,
Password: password,
RememberMe: false
},
returnUrl: returnUrl
}
};
return $http(req)
.then(function (response) {
return response.data;
}, function (reason) {
return reason;
});
};
the response throws me internal error with status 500.
Does angular.js support asynchronous calls to web methods?
Thanks and appreciate your help
If you are using the [ValidateAntiForgeryToken] decorator, the action needs a request verification token to be passed in the post data.
You could remove [ValidateAntiForgeryToken] but this would leave your action open to tampered requests.
The other option is to add an anti forgery token to the page and then pass its value in the request.
Your razor view will need a form with a token in it (Note: This is just a dummy form to allow the token to be added to the page).
#using(Html.BeginForm("Login", "ControllerName", FormMethod.Post, new { id = "verification-form"}) {
#Html.AntiForgeryToken()
}
In your javascript, you can then pass its value
var loginUser = function (email, password, returnUrl) {
var req = {
method: 'post',
url: '/Mysite/Login',
headers: {
'Content-Type': undefined
},
data: {
model: {
Email: email,
Password: password,
RememberMe: false
},
__RequestVerificationToken: $("#verification-form input[name=__RequestVerificationToken]").val(),
returnUrl: returnUrl
}
};
return $http(req)
.then(function (response) {
return response.data;
}, function (reason) {
return reason;
});
};

Resources