i am trying to introduce Angular into one of my old application. But not sure why this is not calling the Service. Below is the Code in the JS File. Earlier i got error in browser saying $http cannot be resolved . So i just passed it in the function.
var app = angular.module('ldlApp', []);
app.controller('ldlController', function($scope,$http) {
console.log(" Inside Controller **** ");
$scope.message = 'Hello from LDL Controller !!!! ';
$scope.BLT_LDL_DECESION_LOAN_DATA = [];
console.log(" Going to Hit the Service ***** ");
$http.get("/Services/ldl/getdetails")
.then(function(response) {
$scope.BLT_LDL_DECESION_LOAN_DATA = response.data;
console.log("BLT_LDL_DECESION_LOAN_DATA:
"+JSON.stringify($scope.BLT_LDL_DECESION_LOAN_DATA));
});
});
Below is the REST Controller in java File
#RestController
public class LoanDecesionController {
#RequestMapping(value = "/Services/ldl/getdetails", method = RequestMethod.GET)
#ResponseBody
#Transactional
public List<LinkedHashMap<String, Object>> getdetails() throws Exception {
System.out.println(" Inside Service **** ");
List<LinkedHashMap<String, Object>> dataMap = new ArrayList<LinkedHashMap<String, Object>>();
LinkedHashMap<String, Object> responsedataMap = new LinkedHashMap<>();
responsedataMap.put("SUCESS", "Called the service ");
dataMap.add(responsedataMap);
return dataMap;
}
}
In Browser i could see message like
Inside Controller ****
Going to Hit the Service *****
Below is something i am seeing in network tab .
Request URL: https://*****-*****-*****.com/Services/ldl/getdetails
Request Method: GET
Status Code: 302 Found
Remote Address: 10.***.***.49:553
Referrer Policy: no-referrer-when-downgrade
But i am not getting the sysouts in controller. So whether the problem is really with response or is it hitting the service.
when using #Transactional and #ResquestMaping spring boot don't auto-configure URL mappings. remove #Transactional from your method and try to manage transactions somewhere else in your code
It looks like my existing application is blocking the URL and not allowing to hit any other URLs . Thanks everyone for the help and giving insight to the problem.
Related
I have a superagent call to my java code. In that Java Controller - I am throwing user defined exception message as below.
In service :
if (user_id == null){
throw new Exception("User ID is missing!!!");
}
In controller:
Map<String, String> resp = new HashMap<String,String>();
try{
String returnValue= myserviceobj.myservicemethod;
}catch(Exception e){
resp.put("status","ERROR");
resp.put("message",e.getMessage());
return new ResponseEntity<Map<String,String>>(resp, HttpStatus.Bad_Response);
}
In React Js I am using superagent to make service call. I am not sure how to access that user defined exception message in UI.
Here is what I do in JS:
webservice(data, actionName, (error,resp){
if(error){
//call alert and send the user defined message.
}
})
https://developer.mozilla.org/fr/docs/Web/API/Window/alert ?
Anyway i would use Redux to check the state of my app and dispatch an alert action.
Maybe this is what your looking for : https://alexanderpaterson.com/posts/showing-and-dismissing-alerts-in-a-react-application
I am trying to do some frontend logging using log4js and sending the logs using the AjaxAppender to the server backend using Java. This is the frontend code that I use to initialize the logger, I've made sure the logger works with a DefaultLogger, and switched to AjaxAppender.
var log = log4javascript.getLogger();
var ajaxAppender = new log4javascript.AjaxAppender("logger");
ajaxAppender.setTimed(true);
ajaxAppender.setTimerInterval(10000); // send every 10 seconds (unit is milliseconds)
log.addAppender(ajaxAppender);
//convert to JSON format
jsonLayout = new log4javascript.JsonLayout(false, false); //readable, combineMessages
ajaxAppender.setLayout(jsonLayout);
ajaxAppender.addHeader("Content-Type", "application/json");
log.info("Begin Session")
This is the backend code written in Java, which gets the logs sent from the frontend.
#RequestMapping(value = "/logger", method = RequestMethod.POST)
#ResponseBody
public String logger(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, IOException, SQLException {
System.out.println("Inside Logger");
System.out.println("Log:"+request);
return "Test successful:" + request;
}
However, I am getting the error XHR failed loading POST and the code doesn't seem to go inside the logger function ("Inside Logger" is not printed in terminal). I'm fairly new to working with Ajax and sending request between frontend and backend, is there a reason why the XMLHttpRequest is not going through?
Thanks!
404 means the service isn't reachable. Are you sure you've started the service and configged it properly?
I am currently trying to develop a simple angular js application.
I am trying to post data from client to web api.
However, I am getting 404 error when I fire post request from angular app.
Below is my post request,
$http.post('/api/LoadApi/', jsonData).then(function (result) {
console.log(result.data);
})
.catch(function (error) {
});
where jsonData is a valid json data.
My web api code is this,
public class LoadApiController : ApiController
{
[HttpPost]
public HttpResponseMessage LoadData(object dataToLoad)
{
var response = Request.CreateResponse(HttpStatusCode.Created);
return response;
}
}
My web api route config is this,
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{dataToLoad}"
);
However, when I run the code, it throws an error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /api/LoadApi/
Can anyone point what is the problem with the above code?
It says there is some problem with url. The url generated is http://localhost:14154/api/LoadApi/ which looks correct.
The issue is with your route definition and how you are trying to send data to your controller method. I would recommend using attribute based routing. In your Web API controller do this:
[RoutePrefix("api/LoadApi")]
public class LoadApiController : ApiController
{
[HttpPost]
[Route("loadData")]
public HttpResponseMessage LoadData(object dataToLoad)
{
var response = Request.CreateResponse(HttpStatusCode.Created);
return response;
}
}
Change the Application_Start() method in Global.asax.cs to this:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Make sure WebApiConfig.cs in App_Start has a Register() method like this:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
And finally change your $http.post call to this:
$http.post('/api/LoadApi/loadData', jsonData).then([...]);
I know how to send a post request with angular to an API, but was wondering how to retrieve post request sent from an application.
Let say I have this C# post request:
public string sendPost(string data)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://localhost:5000/app/edit");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{\"data\":\"" + data + "\"}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
In my angular app I have this controller:
(function () {
'use strict';
angular.module('anbud')
.controller('editController', ['$scope', 'localStorage', 'md5', '$routeParams', 'httpError',
function ($scope, localStorage, md5, $routeParams, httpError) {
function processHeaderData() {
console.log($routeParams.json);
}
processHeaderData();
}]);
}());
I can send data via a the url and use routeParams, but I would like to use POST instead. How do I access the POST data?
I think you are mixing up front end and web server technologies.
Angular is a front end technology, what you mean sending a post to angular, actually means sending a request to the web server that hosts the angular website.
Once you make this clear, you just need to send an API call to the web server like how you do with angular, and the server will return the json data you need.
If you want to get the HTML representation of particular route, I'm afraid there is no good way to achieve this. This is not particular with angular either, any site that loads data with ajax call would have this problem.
Angular $http.post can also retrieve data. For security purposes, this is quite beneficial. Logic for that remains the same.
You could send data from your c# controller through this:
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Sample.API.Controllers
{
public class ContentDataController
{
[Route("api/ContentData")]
[HttpPost]
public HttpResponseMessage SamplePost(SampleRequest request)
{
HttpResponseMessage response;
try
{
var cda = dataContentAdapter();
//Business logic here
var result = cda.GetContent(request);
//pass the above result to angular
response = Request.CreateResponse(HttpStatusCode.OK, result);
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
}
catch (Exception ex)
{
ApplicationLogger.LogCompleteException(ex, "ContentDataController", "Post");
HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } };
return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError);
}
return response;
}
}
}
With this, send a request from angular with whatever data that needs to be used in request. Favorable is to send json, parse the json in your business logic.
Create a HttpResponseMessage with the new payload for angular $http to recieve.
HI i have a micro service running on port 8501.
#RestController
#RequestMapping("/feeds")
public class FeedsController {
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds() {
return new ResponseEntity<String>("Hello", OK);
}
}
when i add url http://localhost:8501/feeds, browser displays "Hello". Now i am trying to access this through angularjs get call
in my AngularJs my code is
'use strict';
var app = angular.module('commentsjsApp');
app.controller('MainCtrl', function ($scope,$http) {
$http.jsonp('http://localhost:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data+ "Status");
}).error(function(){
console.debug("error");
});
EDIT :
In Network tab (firebug) i can see the GET with 200 status and response is "Hello". Why i am getting the error in console then? Can any one kindly help me.
and when i run this angularjs app. the following output on console as shown in image
You are requesting a JSONP data, but the server is returning a string. Return a proper JSON object from the server to fix the issue.
Note: Hello world is not valid JSON, but "Hello World" is.
You need to add the header 'Access-Control-Allow-Origin' in the response, since your calling from localhost:9000 to localhost:8501 (they are technically different servers).
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
httpResponse.addHeader("Access-Control-Allow-Origin",
"http://127.0.0.1:9000");
return new ResponseEntity<String>("Hello", OK);
}
Sometimes Angular requires the colon in the URL to be quoted, try this:
$http.get('http://localhost\\:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data);
}).error(function(){
console.debug("error");
});