post method is not going to success part in angular - java

I am writing an angular with java project for this I have wrote a java rest service and I am calling it from my angular client with post method. it is able to call the rest service but it is not coming to client side.
I kept an alert in success. It is not printing but in chrome network tab the status is showing 200.
Angular: -
uploadFileToActivity() {
const endpoint = 'http://localhost:8090/sendmails';
let config = {headers: new HttpHeaders({})};
const formData: FormData = new FormData();
formData.append('fileupload', this.fileToUpload);
this.httpClient.post(endpoint, formData).subscribe(data => {
alert();
})
}
Java service: -
#PostMapping(value = "/sendmails", headers = "content-type=multipart/*")
public ResponseEntity<String> sendEmails(#RequestParam("fileupload") MultipartFile ExcelDataFile) {
return new ResponseEntity<String>("Success", HttpStatus.OK);
}
I want to do some functionality in success, but the call is not coming to success part.
I got an error in the console.
error: {error: SyntaxError: Unexpected token S in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "Success"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8090/sendmails"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8090/sendmails"
__proto__: HttpResponseBase

You are returning a text and not a JSON object from your java service. You can fix this by specifying the responseType in your post call:
this.httpClient.post(endpoint, formData, { responseType: 'text' })
You can also think about returning a JSON from your JAVA endpoint, but that's up to you

Related

Backend return html but frontend does not redirect

I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', headers: headers, body:
JSON.stringify(payload) })
.then((response) => response.json());
}
Is there something I'm missing?
try to help but with this snippet, you didn't show your "redirect part" if you are using reactjs you should have a look at DOM Router and using Redirect or push history.
You should use redirect: 'follow' in the request options.
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', redirect: 'follow', headers: headers, body:
JSON.stringify(payload) })
}
If you want to know the redirect url and do manual operation, you have to use redirect: 'manual'.
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', redirect: 'manual', headers: headers, body:
JSON.stringify(payload) })
.then((response) => {
const redirectUrl = response.url // new redirect url
})
}
Hope this helps!

React fetch to Java backend returning null

I currently have a react button that should be sending data from the state to a servlet via post. The server is getting hit from the fetch method but the data appears to be null.
fetch(
"http://localhost:8080/askQuestion",
{
method: "post",
body: {
question: this.state.value
},
headers: {
"Content-Type": "application/text"
}
}
).then(console.log(this.state.value));
The value in my request object for both body and question are null
request.getParameter("question");
request.getParameter("body");
You can use getInputStream() or getReader() to read body attributes of the requests.
Here is an easy (not conventional) way to get your work done:
Write your body attributes in headers:
headers: {
"Content-Type": "application/text",
'question': this.state.value
}
In backend, use request.getHeader("question") to get the value.
You can try sending json data as the body of your post request
fetch('http://localhost:8080/askQuestion', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({ question: this.state.value })
}).then(res => res.json())
.then(res => console.log(res));

Spring Rest Service throwing HTTP Status 415

Hi I am trying to call a Spring rest service from angular but I am getting the below error. Even from The Postman I am getting the same error.It looks like something is wrong with the rest service, which is not accepting the json request data
HTTP Status 415 : The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. Thanking everyone in advance.
Below is the code
**Angular Code**
var req = {
method: 'POST',
url: 'http://localhost:9050/FastTrackALM/retrieveData/getEpicData',
headers: {
'Content-Type': 'application/json'
},
data: {'epicId': '1' }
}
$http(req).then(function(response){
console.log(response);
}, function(response){
console.log(response);
});
**REST SERVICE**
#RequestMapping(method=RequestMethod.POST,
value="/getEpicData",
consumes={"application/json"},
produces={"application/json"})
#ResponseBody
#ResponseStatus(code = HttpStatus.OK)
public DataActionObject insertStudentDetails(#RequestBody epicForm1 student){
DataActionObject dataActionObject = new DataActionObject();
dataActionObject=epicBusinessBean.getEpicData(student.getEpicId(), dataActionObject);
return dataActionObject;
}
DataActionObject is my custom class that holds the json date to be returned to client along with message an code

Response for preflight has invalid HTTP status code 401 and i used cross origin plugin

var req = {
method: 'GET',
url: holaRootUrl + action,
headers: {
'Authorization': 'Bearer ' + $rootScope.accessToken
},
params:params
}
$http(req).success(function () {
console.log("yes you have done it");
}).error(function () {
console.log("oopsss");
});
this is what I got :Response for preflight has invalid HTTP status code 401
After the discussion in comments, the issue got narrowed to authentication on OPTIONS calls and in result sending the 401 Unathorized code.
I don't know JAVA to well but try something like this before applying authentication check
if ( request.getMethod().equals("OPTIONS") ) {
resp.setStatus(HttpServletResponse.SC_OK);
return;
}

XMLHttpRequest Exception 101 when i try to call POST rest with jquery

i'm using jquery ,jersey and json.
when i try to call a post service i receive this error
Origin null is not allowed by Access-Control-Allow-Origin.
undefined * Error: NETWORK_ERR: XMLHttpRequest Exception 101
My client code
$.ajax({url: jurl, type: 'POST', dataType : 'json', headers: {accept:"application/json"},data: inData , cache : false, async : false, contentType : "application/json; charset=utf-8",
My server Code
#POST
#Path(ReferentialPath.PLAYER_RESOURCE_PATH)
#Consumes(MediaType.APPLICATION_JSON)
public Response createPlayer(CreatePlayerIn cPlayer) {
try {
String res = dao.create(player);
UriBuilder ub = uriInf.getAbsolutePathBuilder();
URI createdUri = ub.path(res).build();
return Response.created(createdUri).build();
} catch (Exception e) {
}
}
Would anybody tell me what could be the problem
you seem to be trying to POST to another domain.
possible problem wiki
possible solution :you should read this SO question
Here I guess there must be some firewall between your client and server. HTTP Code 101 represents that your http request be filtered by your net work device. so change your net work and directly connect your server. and try again.

Categories