Passing multiple parameters from angular to rest service - javascript

I am trying to pass the data to my rest services through $http.get() using URL.There are 10-12 parameters which I need to pass.
Angular script.js
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
The scope variables would come as undefined sometimes.But I guess that will not be a problem.I checked the console, the URL is getting formed correctly with all 12-13 parameters.
Now I am trying to get this in rest service using #QueryParam like below -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
The problem is that the #QueryParam is working for 2 parameters but when I am increasing the number of parameters, it is failing. As per the browser console, I am getting 404 error.
Is there any limitation to the number of parameters we can pass? I need to pass 12-13 parameters.How can I achieve this?
Update -
I was able to resolve my issue . I was using Date datatype in #QueryParam because of which it was throwing 404 error . Changed it to String and it worked . Did not know that we cannot use Date in QueryParam .
Apologies for not putting the detailed problem .

If you want to do it in the proper RESTful way then you can try like this, I have given it for couple of variables, but you can do for any.
#RequestMapping(path = "/rest/test/getAllData/{filter1}/{filter2}", method = RequestMethod.GET)
public Data getAllData(#PathVariable String filter1, #PathVariable String filter2) {
// code here
}
You can also achieve it using RequestParam, an example below, ensure your parameters matches
#RequestMapping(path = "/rest/test/getAllData", method = RequestMethod.GET)
public Data getAllData(#RequestParam String filter1, #RequestParam String filter2) {
// code here
}
If you still have a complicated structure then send it as a POST with the JSON data in the request body
#RequestMapping(path = "/rest/test/getAllData", method = RequestMethod.POST, consumes = "application/json")
public Book getAllData(#RequestBody ObjectKey objectKey) {
// code here
}

For passing more number of parameters, you can use Rest parameter. It is used to access indefinite number of arguments passed to a function.
Syntax :
function add (...numbers){}

const params = new HttpParams()
.set('paramName1', value1)
.set('paramNmae2', value2);
return this.httpClient.get<IMyObject[]>(this.myUrl, {params} ).pipe(
tap(data=>console.log('ALL:'+JSON.stringify(data))),
catchError(this.handleError));

Related

how to read correctly a complex object sent to the back-end

EDIT:
after some tips i edited my code and now i created an object witch contains all my datas as i intended to have it, so now i have an object composed of an int and an array of another object that has an array on the inside
here is the code of the objects:
export class tempfp{
mesi: fp[] = []
id:number=0;}
export class fp{
arr:number[]=new Array();}
this is what i do before to send the data to my backend
(note that the object data has an any type and the object send is a tempfp)
async onSubmit() {
console.log("start: \n"+JSON.stringify(this.data))
for (let i = 0; i < this.data.length; i++) {
let m = new fp();
Object.assign(m.arr, JSON.stringify(this.data[i]));
this.send.mesi[i] = m;
}
this.send.id=this.id;
this.efp.postarray(this.send)//i even tried to put in this function this.data instead of this.send
}}
in my back-end i have the same objects, but when i send the datas using an http post it does not read it correctly indeed when i try to manipulate the datas from the back-end i get error 500 in my browser, and if i try to print this thing in my back-end it looks empty
A post request can have only one body and you're already passing a body, what you need to do is create a model in java that represent the body you want to pass and then pass it from the front end.
//I like to use lombok's #Data annotation to generate getters setters
//and default constructor but you can also write them by hand
#Data
public class MyBody {
private String eff;
private int id;
}
then in your controller you will accept ad body an instance of this model.
#PostMapping("takearrfp")
public void takearr(#RequestBody MyBody body) {
String eff = body.getEff();
int id = body.getId(); //And then do what you want whit this
efps.readAndSave(eff);
}
At this point the only thing remaining to do is passing this model as a body, so you will need to pass as body of the post request an object with the same fields
{
eff: put something here,
id: put the id here
}
What you have to do is simple. As the other answer also said you can only pass only one body at a time. so if you want to include the id then you have to put it into the body. Just try the below code
const body = {
id: id,
arr: arr
}
const obj = JSON.stringify(body)
Then you can read those data from the back end by using the suggested approach from Fabrizio's answer.

How can I access parameters from a POST (or other HTTP) request in a C# server?

I'm building a Reactjs application using ASP.Net Core, and I'm completely new to this. I have a JS component that (to the best of my knowledge) is making an appropriate fetch request (POST) to a C# server controller. The server is definitively receiving the request. However, I have absolutely no idea how to access the parameters of the request (which I am passing through the body).
I've tried using [FromBody] to access the body directly. I've also tried to utilize the Request.Body, the Request.Form, the Request.Query, the Request.Params, etc. I've attempted to follow the guidelines I've found online that seem to try to address my problem. Several of them flat-out haven't worked. Most of them are using key words, classes, etc. that are not available to me in my current libraries, and they don't list the appropriate libraries. For all I know, I've stumbled across the right answer already. But for someone like me with a highly logical mind but also pretty much zero experience in the field, I can't wrap my mind around any of it.
My POST request using fetch in JavaScript:
fetch('api/Database/PushStatus',
{
method: 'post',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ order: this.state.orderNum, status: this.state.newStatus })
}
).then(response => {
response.json().then(data => {
this.setState({ reqCheck: "" + response, didPush: false });
})
}).catch(err => {
this.setState({ reqCheck: "Failure! (js)", didPush: false })
});
And my request handling on my C# server:
[Route("api/[controller]/[action]")]
public class DatabaseController : Controller
{
string conStri = "Data Source=ADM293\\MSSQLSERVER01;Initial Catalog=testDB;User ID=sa;Password=password.1";
SqlConnection cnct = null;
[HttpPost]
public void PushStatus(string order, string status)
{
cnct = new SqlConnection(conStri);
SqlCommand command = new SqlCommand("insert into testTable values ('" + order + "', '" + status + "');", cnct);
using (cnct)
{
cnct.Open();
int result = command.ExecuteNonQuery();
cnct.Close();
}
}
}
I would like my server to be updated with the contents of this.state.orderNum and this.state.newStatus.
Instead, my server is updated with empty string values (which makes perfect sense).
You can create a class that represents the request:
public class PushStatusRequest
{
public string Order { get; set; }
public string Status { get; set; }
}
And use it like this:
[HttpPost]
public void PushStatus([FromBody] PushStatusRequest request){
//request.Status
//request.Order
}
#Anteo is right. But I would like to add some explanation.
You have faced two different ways to pass params to a controller.
You try to use a body (setting body in request) as an entrance and the query (in the controller) as an output.
Well, body is one type and it requires to be some model on a Controller side. Use [FromBody] to automatically retrieve your data from a request into a model. Create this model as a separate class following the same naming politics (ignoring case).
Then, a query string is what you are using at the controller side. On a request side, it follows the URL like this: https://host:port/route/to/then/query/params. So, if I am not mistaking a base URL is a part https://host:port. Everything is left is a query string. A part of that is being mapped to the route to your controller's action. Anything left is interpreted as useful info and mapped to an action params.
So, here is the moment for you to choose (depending on the length of your orderNum and newStatus) which approach to use. I would recommend using the body as it is more data than routing.
Also, If you inherit [ControllerBase][1], then you can use Request property in action to access the request itself. But be careful here.
P.S. I would recommend you to read more about requests, things like form data, body, queries, etc.
If have any further questions feel free to ask.
By default, capitalization changes between JavaScript and C#. So, you probably just need to change your method signature:
public void PushStatus(string Order, string Status)
That said, having the class the way #Anteo suggested is usually better. Also, I assume you put SqlConnection just for clarity. You shouldn't do it in the controller

passing non-url encoded parameters to an ajax call in node.js

I am trying to pass parameters from my website to a couchdb server through a node.js server.
I absolutely need to pass {} in a url. Not a string, not an empty object, the actual {} characters. It is used to define the end_key parameter in couchdb views.
At the moment, my call goes like this :
let url = "/trades";
let ajax_options = {
data:{
design_name:'bla',
view_name:'blabla',
params_view:{
group_level:2,
start_key:["1",0],
end_key:["1",{}]
}
}
};
$.ajax(url,ajax_options).then((res) => { ... });
when it passes through NodeJs and the nano library with
db.view(req.query.design_name, req.query.view_name, req.query.params_view)
the end_key object in params_view becomes ["1"] instead of ["1",{}] which I would like to see.
I have verified that with the correct value for end_key, the view gives me the expected result.
How to prevent that behavior from occurring ?

send String from java to js, using current project

Before ask this question, I have already read the forum and tried a lot of from forum suggestions. I do not know , maybe i do not clearly understand or maybe the reason that i apply to my current project, however answer on the forum is not working in my project
Java:
#RequestMapping(value = "/warehouseWhisky", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView viewAllWhiskyInWarehouse() {
Iterable<WhiskyDTO> list = whiskyService.seeAllWhisky();
String email = receiveEmailFromSecurity.getEmail();
System.out.println(email);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("viewAvailableWhisky", list);
modelAndView.addObject("email", email);
modelAndView.setViewName("whisky");
return modelAndView;
}
This code correct, I recive in HTML string:
<input type="button" id="someThingNew" th:value="${email}"/>
But I didn't recieve this parameters in js:
var nameUser = $("#someThingNew").val();
console.log(nameUser);
I think the problem is caused because of the special characters in email like '#'. In other word you cannot send email address using #PathVariable (with ordinary routing configuration). Instead of #PathVariable, you can send email using #RequestParam and send it as a query parameter.
I think the first method is probably fine - just you are calling the wrong URL. What is your server mapping? I would expect something like -
http://localhost:8080/warname/warehouseWhisky/test#test.com
The issue with the second one is that its expecting similar to the following - which is why you are getting a 500
#RequestMapping(value = "/warehouseWhisky/{email}")

Error using dynamic keyword in asp.net mvc 4

I am getting this long error when i accpet the parameter as dynamic on my server side action method in mvc 4.
{"Message":"An error has
occurred.","ExceptionMessage":"'Newtonsoft.Json.Linq.JObject' does not
contain a definition for
'TournamentId'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":"
at CallSite.Target(Closure , CallSite , Object )\r\n at
System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite
site, T0 arg0)\r\n at
ManagerDeTorneos.Web.Controllers.TournamentDateController.Create(Object
data) in
F:\Prince\Projects\Juan\trunk\ManagerDeTorneos.Web\Controllers\TournamentDateController.cs:line
133\r\n at lambda_method(Closure , Object , Object[] )\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c_DisplayClass13.b_c(Object
instance, Object[] methodParameters)\r\n at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object
instance, Object[] arguments)\r\n at
System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1
func, CancellationToken cancellationToken)"}
[HttpPost]
public HttpResponseMessage AddMatch(dynamic data)
{
int tournamentDateId = (int)data.TournamentDateId.Value;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
In The above method data Contains tournamentId as sent from ajax call as JSON.Stringify({'TournamentId':'5'}).
Can anybody tell me what is the cause of error. I even replaced the dll of Newtonsoft.Json as well
You are right dan but i fixed my issue by removing that dll from GAC. May be in GAC it was using old assembly
The error is caused by the fact that you typed your parameter as dynamic, which means that the model binder doesn't know what to make it. It's the same as if you were to declare it as an object. Since you are providing JSON, it serializes the object as a Json.Net JObject. Just because you define it as a dynamic doesn't mean that it's going to magically take whatever shape you need it to.
Change it to a concrete type - something that matches the structure of the provided JSON:
public class TournamentInfo
{
public int TournamentId { get; set; }
}
[HttpPost]
public HttpResponseMessage AddMatch(TournamentInfo data)
{
int tournamentDateId = data.TournamentId;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
This way, the binder knows what it's supposed to turn the JSON into, and since TournamentInfo matches the structure of the JSON, it won't have any trouble serializing it.
Don't misuse dynamic. It was not introduced into C# so developers could stop defining classes.

Categories

Resources