I was having some problem when trying to pass a parameter from jsp to controller. Here is the JavaScript where I call the API in Controller:
function help(value){
// need to pass the "value" parameter to this following API
window.open("<c:url value='doWavierGuide.do'/>", 'info', 'width=640,height=480,resizable=yes,scrollbars=yes')
}
And my controller as such:
#RequestMapping(value = "/doWavierGuide.do", method = RequestMethod.GET)
public ModelAndView showWavierGuide() {
Map<String, Object> modelMap = new HashMap<>();
log.debug("showWavierGuide() : Method is ");
// need to put the value passed in from javascript into here, temporary hardcoded
modelMap.put("method", "1");
return new ModelAndView("wavierGuide", modelMap);
}
But I not sure how can I pass the value from JavaScript to Controller. If I hardcoded the parameter value in Controller, the page managed to display. Any ideas? Thanks!
I managed to solve it by changing the url in jstl tag like this:
"<c:url value='doWavierGuide.do?method='/>"+value
And in the controller, retrieve the parameter using HttpServletRequest:
#RequestMapping(value = "/doWavierGuide.do", method = RequestMethod.GET)
public ModelAndView showWavierGuide(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
modelMap.put("method", request.getParameter("method"));
return new ModelAndView("wavierGuide", modelMap);
}
You have to use a library to make http requests to the server, or use fetch to send and receive data.
I leave an example:
const cnn = async (path, options) => {
const url = "www.example.com";
let result = await fetch(`${url}${path}`,
options
);
if (result.status >= 200 && result.status <= 299) {
return await result.json();
}
return { data: null, error: true }
}
// request to the API
cnn("doWavierGuide.do", { method: "GET", body: {name: "you_name"} })
.then(response => response.json())
.then(response => console.log(response))
Related
I currently not sure how to use a fetch post call to pass an object to a method expecting that object. I created a payload and passed it but does not seem to work. I have set a breakpoint in the code behind but it is never hit. Not sure why the fetch call is not working. Any suggestions on way the endpoint is not being reached?
This is my method in C#.
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword(Player player){
{
Javascript:
const continueBtn = document.getElementById("continueBtn");
continueBtn.onclick = () => {
const email = document.getElementById("lblEmail").innerHTML;
sendResetEmail(email);
}
async function sendResetEmail(email) {
const payload = {
email: email
}
const data = new FormData();
data.append("json", JSON.stringify(payload));
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
body: data
});
}
if you don't want to provide the name of the parameter in your client, you need to give the [FromBody] attribute in your API:
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword([FromBody] Player player){
}
Then, on the client, there are multiple ways, but the most common/modern is to use JSON encoding:
const payload = {
email: email
}
const data = JSON.stringify(payload);
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
}
I am trying to debug the response from a post call. The post succeedes and the response is shown inside the response tab in the Chrome developer tools but the promise callback is never triggered.
Any idea why the callback is not triggered?
Here is the subscription:
this.mService.uploadFiles([file.name, new Blob()]).subscribe((response: any) => {
var myResponse = response;
//Do something with response
},
error => {
var err = `Failed with status = ${error.status}`;
});
Calling the Rest API:
public uploadFiles(files: any): Observable<any> {
let formData = new FormData();
formData.append('file', files[1], files[0]);
return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {
observe: 'response'
}).pipe(map(response => response))
}
I am actually getting the following error even though the POST succeeds. Probable related to how the service is subscribing.
core.js:4002 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:28)
at subscribeToResult (subscribeToResult.js:15)
at CatchSubscriber.error (catchError.js:43)
at XMLHttpRequest.onLoad (http.js:1707)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:26247)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
at invokeTask (zone.js:1693)
[UPDATE]
Below is the server side code for the called Azure Function
[FunctionName("UploadFiles")]
public async Task<IActionResult> UploadFiles([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequest req, ILogger logger)
{
return (ActionResult)new OkObjectResult("Testing");
}
In this case Chrome displays the Testing string in the response tab. The callback is however not triggered.
... but if change the code to only return a OkResult the callback is triggered. So it seems the error appears only if the OkResult contains a payload. Any clue why this is failing?
return (ActionResult)new OkResult();
Give this a try do return response
public uploadFiles(files: any): Observable<any> {
let formData = new FormData();
formData.append('file', files[1], files[0]);
return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {headers : new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})}).pipe(
map((response: Response) => {
return response;
})
)
}
whenever you do map in service like this do return that value so that mapped value will be return where you subscribing this service
EDIT
Try passing headers since you are passing file object in api
you can try like this
component
this.mService.uploadFiles([file.name, new Blob()]).subscribe((response: any) => {
var myResponse = response;
// here we are doing other operations like filtering and mapping etc..
myResponse.pipe(map(result => { console.log(result); }))
},
error => {
var err = `Failed with status = ${error.status}`;
});
service
public uploadFiles(files: any): Observable<any> {
let formData = new FormData();
formData.append('file', files[1], files[0]);
return this.http.post(`${this.myServiceEndpoint + "api/uploadFiles"}`, formData, {
observe: 'response'
});
}
Turns out I had to convert the response to json format on the server side (thought this was default json) and escaping the string quotes because the Angular interseptor was expecting json:
[FunctionName("UploadFiles")]
public async Task<IActionResult> UploadFiles([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequest req, ILogger logger)
{
var jsonResponse = JsonConvert.SerializeObject("Testing");
return (ActionResult)new OkObjectResult(jsonResponse);
}
and the callback is triggered successfully.
Why I can't sent FormData object values to my Laravel application
Javascript code:
console.log("Sending start...")
for (var value of company.values()) {
console.log(value);
}
this.$axios.put(url, company)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
Response preview:
Laravel controller:
public function update(Request $request, Company $company)
{
return response()->json($request->all());
}
Where I've any error?
Try to trick the Laravel framework by sending a POST request with axios assigning method type as PUT to FormData object.
Code:
// Lets create FormData object
let data = new FormData()
data.append('_method', 'PUT')
// ...........................
// other your appends here...
// Axios request
this.$axios.post(url, data)
.then(res => {
console.log(res)
})
After checking, let me know about the result of the code :)
I know about how to pass data between javascript and c# by ajax, and now I want to know fetch.
c#:
namespace WebApplication1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
javascript:
fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
.then(response => {
alert(response.json());
})
.then(response => {
alert(response);
})
it showed:
The usage of this url is based on ajax.
I changed the url to "http://localhost:62177/WebService1.asmx?op=HelloWorld", it showed:
I thought it was response success, however I received nothing and it showed:
Then I modified the method of return data, now it was json-format :
c#:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public void HelloWorld()
{
object JSONObj = JsonConvert.SerializeObject("Hello World");
Context.Response.Write(JSONObj);
}
But there was no change.
I don't know how else to change it. Can someone give me a little help?
The output of your web service doesn't produce JSON. It outputs "Hello World" when it should say something like:
{"YourKeyHere":"Hello World"}
I'd change the web service code to something like this:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat System.Web.Script.Services.ResponseFormat.Json)]
public void HelloWorld()
{
var obj = new { YourKeyHere = "Hello World" };
string JSONObj = JsonConvert.SerializeObject(obj);
Context.Response.Write(JSONObj);
}
At the top of your web service, uncomment this decoration: [System.Web.Script.Services.ScriptService]. It needs to be uncommented so that JavaScript (and maybe other clients) can see your service.
In your JavaScript, your response will come back as text (not json), and it will come with a {"d":null} bracket appended to it. To clean this up, I used substrings and placed them in a different function:
function SayHello()
{
//...
var options = {
method: 'GET' ,
headers: {
'Content-Type': 'application/json',
}
};
fetch("http://localhost:62177/WebService1.asmx/HelloWorld", options)
// Handle success
.then(response => response.text())
.then(result => DisplayResponse(result))
.catch(err => console.log('Request Failed', err));
//...
}
function DisplayResponse(result) {
console.log(result); //not sure why 'd:null' shows in output
console.log(result.substring(0, result.indexOf('{"d":null}'))); //get rid of 'd:null'
console.log(JSON.parse(result.substring(0, result.indexOf('{"d":null}')))); //get rid of 'd:null' then parse
}
You first need to make sure that your server is returning something in JSON format. But in addition, in your JS, you have to return the response.json() (or the response.text() or whatever method is appropriate) infetch` so that the stream can be processed, so that you can get a response in the next function:
fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
.then(response => {
return response.json();
})
.then(responseJSON => {
alert(responseJSON);
})
The initial response is a response stream object, which doesn't actually contain any data yet.
I do the filtering, when I click on the apply filter, the query in the API flies away
php-developer, says that the request should be get, not post
how to pass parameters to the get query?
example for my post request
export const filterDate = (options) => {
console.log(options)
return axios.post(url, options).then(({ data }) => {
if (data.errors) throw new Error(JSON.stringify(data.errors));
return data;
})
};
but if I just replace the post on the get parameters are not transferred
If you want to pass parameters in get request, pass an object with "params" property, as follow:
axios.get('/user', {
params: {
ID: 12345
}
});
in options you specify a param object:
params: {
k: val
},
or by building an UrlSearchParam object:
const params = new URLSearchParams();
params.append('k', 'val');
axios.get(url, params);