i use node.js as server and android as client, the server work normally send and receive data from client (except android)
here my code in javascript
function put(id, data, callback) {
$.ajax('http://mydomain.com:8888/' + id + '/', {
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function(data) {
if (callback)
callback(data);
},
error: function() {
if (callback)
callback(false);
}
});
}
and my node script
function handler ( req, res ) {
if ( req.method === 'POST' ) {
console.log('receive data from post');
}
}
the code above has successfully sent data.
i want to send data (post) to node (like what javascript does) in android?
how i achieve that?
thanks
But of course
Here you go
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Related
I'm working on an app for a school project. I'm trying to fetch a string in react, the backend has been build with C#. In the backend i'm sending a HttpResponseMessage with StringContent to the client side. But i can't seem to read the StringContent at the client side.
The Api at server side:
[HttpGet("{id}")]
public async Task<HttpResponseMessage> downloadDocument(int id)
{
try
{
string base64String = await this.DocumentService.downloadDocument(id);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(base64String);
return response;
}
catch (Exception ex)
{
var response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
response.Content = new StringContent(ex.Message);
return response;
}
}
The Client side code
function downloadDocument(param: any) {
fetch(process.env.REACT_APP_API_URL + 'document/' + param.row.id, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
}
Where i log data to the console i get the following:
I can see the content object there. but how do i get the string i've added in the HttpResponseMessage with new StringContent(base64String);
I have written the following code to establish connection with signalR server and invoke a hub method:
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/signalRServer").withAutomaticReconnect().build();
connection.start().then( result => {
console.log("RealTime connection is now established")
});
function ShowMessageAndUpdate(messageId, data){
$('#messageModal').modal('show');
$('#mainTxt').text(data);
var formData2 = new FormData();
formData2.append("messageId", messageId);
$.ajax({
type: "POST",
url: "Messages/UpdateMessageStatus",
contentType: false,
processData: false,
data: formData2,
success: function (response) {
if (response.success) {
console.log("status changed successfully!");
var table2 = $('#table2').DataTable();
table2.ajax.reload();
connection.invoke("MessageUpdate", messageId).catch(function(err){
return console.error(err)
});
} else {
console.log("status change failed.");
}
},
error: function (error) {
console.log(error);
}
});
}
</script>
The hub method is invoked when the success response of jQuery is True.
The problem is that console cannot establish a connection with the hub.
Messages:377 Error: Failed to invoke 'MessageUpdate' due to an error
on the server.
at H. (signalr.js:1:13973)
at L.I (signalr.js:1:14804)
at X.L.connection.onreceive (signalr.js:1:10649)
at WebSocket.r.onmessage (signalr.js:1:27565)
Is there anything wrong with my client side code?
Update:
method in the hub is as follows:
public async Task MessageUpdate(int messageId)
{
int destination = _messageRepository.GetSenderIdByMessageId(messageId);
string username = _userRepository.GetUserNameById(destination);
var userId = NtoIdMappingTable.GetValueOrDefault(username);
await Clients.User(userId.FirstOrDefault()).SendAsync("ReceiveMessageUpdate");
}
The problem is in client side, because method is not run when debugging. connection cannot be established correctly when it gets parameter from function(parameter).
UPDATED with res.send(data) instead of res.json(data)
Using Angular 6 and NodeJS I am doing a web application.
I am trying to download a file from a http post request.
I send a request to the server like this. From my component I call a function in a service. In the component, I susbscribe to have the answer of the server and when I have it I create a new Blob with the response and I Use FileSaver to download the pdf.
Now, when I received the answer from the server, the client sees it like an error whereas the status is 200. The error message is:
"Http failure during parsing for http://localhost:3000/api/experiment/regression"
See the screenshot below.
Component.ts
this.api.postML(this.regression).subscribe(
res => {
console.log(res);
let pdf = new Blob(res.data, { type: "application/pdf" });
let filename = "test.pdf";
FileSaver.saveAs(pdf, filename);
},
err => {
alert("Error to perform the regression");
console.log(err);
}
);
API.Service.ts
public postML(data): Observable<any> {
// Create url
let url = `${baseUrl}${"experiment/regression"}`;
let options = {
headers: { "Content-Type": "application/json", Accept: "application/pdf" }
};
// Call the http POST
return this.http
.post(url, data, options)
.pipe(catchError(this.handleError));
}
Then from the server, it executes some code with the data sent and generates a PDF file.
Then, I would like to send the pdf as a response to the client.
I tried like this:
fs.readFile("/home/user/test.pdf", function(err, data) {
let pdfName = "Report.pdf";
res.contentType("application/pdf");
res.set("Content-Disposition", pdfName);
res.set("Content-Transfer-Encoding", "binary");
console.log(data);
console.log("Send data");
res.status(200);
res.send(data);
});
In the client, I have the answer. The console log is:
Finally, I found a video tutorial and it was very basic.
Node.js Server:
const express = require("express");
const router = express.Router();
router.post("/experiment/resultML/downloadReport",downloadReport);
const downloadReport = function(req, res) {
res.sendFile(req.body.filename);
};
Angular Component:
import { saveAs } from "file-saver";
...
download() {
let filename = "/Path/to/your/report.pdf";
this.api.downloadReport(filename).subscribe(
data => {
saveAs(data, filename);
},
err => {
alert("Problem while downloading the file.");
console.error(err);
}
);
}
Angular Service:
public downloadReport(file): Observable<any> {
// Create url
let url = `${baseUrl}${"/experiment/resultML/downloadReport"}`;
var body = { filename: file };
return this.http.post(url, body, {
responseType: "blob",
headers: new HttpHeaders().append("Content-Type", "application/json")
});
}
First of all sorry for my English...
I have an asmx in C# that send data in json with an fetch API Call in the client side, i was using the jQuery.Ajax call before, but i want to start using fetch API.
This is how i do the Fetch Call.
I call the function fetchcall passing the url and if is needed the JS object with the parameters to be send by POST
const jdata = await fetchcall(url, "")
Then in my function i do this
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json'
//credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
const response = await fetch(url, PostData)
const json = await (handleErrors(response)).json();
//This is a temporary solution to the problem
if (json == 'Su sesion ha expirado favor de ir a pagina de login e iniciar session') {
alert(json);
return false;
}
return json
} catch (e) {
console.log(e)
}}
And this is the handleErrors function
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
Right now i am testing the error without sending the credentials, so i get a error for the Session
And in my C# asmx i have this
[WebMethod(Description = "Load Countries", EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string fillcbocountries()
{
var authCookie = Session["uid"];
if (authCookie == null)
throw new Exception("Your session has expired please go to login page and start session");}
With that the web services is throwing me an error with the message of Your session has expired please go to login page and start session
But wen i check the response of the fetch API in the handleError function i only get a statusText:"Internal Server Error" and i want the message that the server respond.
With jQuery.Ajax i do this
error: function (xhr, textStatus, error) {
var errorM = $.parseJSON(xhr.responseText);
console.log(errorM.Message)
}
And i get the
Your session has expired please go to login page and start session
Thank you for the help and regards
I discovered how to handle the error correctly if an exception is sent from C#
I removed the handleErrors function and check the response inside the fetchcall
so if the response.ok is false then i check the json data that the server respond and get the json.Message.
This is the end code
async function fetchcall(url, data) {
const PostData = {
method: 'POST',
headers: {
"Accept": "application/json",
'Content-Type': 'application/json; charset=utf-8'
},
dataType: 'json',
credentials: 'include'
}
if (data) { PostData.body = JSON.stringify(data) }
try {
//const url = 'services/common.asmx/fillcbopais'
const response = await fetch(url, PostData)
const jdata = await response.json();
if (!response.ok) {
alert(jdata.Message);
throw Error(jdata.Message)
}
return json
} catch (e) {
console.log(e)
}}
In case someone else has this problem I hope I can help
I'm trying to upload files using Angularjs for REST API exposed via Spring :
This is my Controller:
#RequestMapping(value = util/images/{partyId},
method = RequestMethod.POST)
public JsonNode uploadPartyRefImage(#RequestPart("file") MultipartFile inputFile,
#PathVariable String partyId){
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jNode = null;
try {
String[] fileInput = ((DiskFileItem) ((CommonsMultipartFile) inputFile).getFileItem()).getName().split("\\.");
Path storagePath= Paths.get(uploadPath);
FileSystemUtil.writeFile(storagePath,inputFile.getInputStream());
jNode = objectMapper.readTree("{\"type\":\"" + "success" + "\",\"fileStorePath\":\"" + pathString + "\"}");
} catch (Exception exApi) {
LOGGER.error("Error uploading Party attached Image "+ exApi);
}
return jNode;
}
This API works fine when used via Postman. The Postman call:
But when calling through angular it throws Exception:
Angular service:
function uploadImage(formData,partyRefId){
console.log(utilService);
if (utilService) {
return utilService.request({
method: "POST",
resource: "/images/" + partyRefId,
headers: { 'Content-Type': undefined},
processData: false,
transformRequest: angular.identity,
mimeType: "multipart/form-data",
cache: false,
data: formData
})
.then(function (data) {
if (data) {
return getResultDataFromResponse(data);
}
}, function (error) {
console.log('error invoking document upload service', error);
});
}
}
Angular Controller:
$ctrl.uploadDocument = function () {
var formData = new FormData();
formData.append("file", k.documentfile.lfFile);
var fileName = "PARTY01" + k.documentReference;
fbeOnboardingWizardService.uploadImage(formData,fileName)
.then(function (data) {
if(data.type == "success")
console.log(data.fileStorePath);
},function (error) {
console.log(error);
});
};
Error in Jboss:
02:06:25,442 WARN [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] (http--0.0.0.0-8080-4) Handler execution resulted in exception: Content type 'null' not supported
If I update the Content-Type to "multipart/form-data" in angular service
Error in Jboss:
Servlet.service() for servlet appServlet threw exception: org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found