I am trying to view file in browser in new tab but in service i am not getting any response and it is throwing me in catch handler of my service and in handler
i am not getting any specific error to troubleshoot the problem.
I am sending Authorization token in header because my view document api is protected.
Also there are 2 below calls going on which i dont understand why :
Call1
Call2
Code :
Controller:
viewFile(index) {
this.FileService.view("f819f948-b5dd-4478-ad69-b0e610627375").subscribe((response) => {
if (response.message === "success") {
window.open(this.baseUrl + response.id, '_blank');
}
}),
(error) => {
console.log('error');
}
}
FileService.ts
view(id): Observable<any> {
return this._http.get<any>(this.baseUrl + 'example/document/' + id)
.catch(this.handleError);
}
handleError(error: HttpErrorResponse) { //always throwing here
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
console.log(error);
}
return new ErrorObservable(
'Something bad happened; please try again later.');
};
Webapi core: Supporting method
IServiceContext _ctx;
Stream stream = repo.GetFileStream("abc.pdf", filePath);
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
_ctx.req.HttpContext.Response.Headers.Add("Content-Disposition", "inline; filename=" + "abc.pdf");
var provider = new FileExtensionContentTypeProvider().
TryGetContentType("abc.pdf", out string contentType);
_ctx.req.HttpContext.Response.ContentType = contentType;
stream.CopyTo(_ctx.reqobj.HttpContext.Response.Body);
stream.Flush();
I am not getting whats the issue here and most importantly why there are 2 get calls?
When i call my view api document api in postman then i can see the file and also when i go in preview of Develer tool in chrome then i am able to see the image but it is not working with angular js.
Am i missing anything from server end or something is wrong in client side?
I will appreciate any help :)
Related
In Spring Boot, when we try to send a Server Sent Event, it only sends an error event containing data: {"timeout":-1} when we try to connect, and the connection closes. The Spring Boot class is as follows
#RestController
#CrossOrigin(origins = "*")
public class SsePushNotificationRestController {
private static final Logger log = LoggerFactory.getLogger(SsePushNotificationRestController.class);
private SseEmitter emitter;
#GetMapping("/test")
public String getString(){
try {
emitter.send("User connected");
log.info("User connected");
emitter.complete();
} catch (Exception e) {
log.info("Error while sending message to client: " + e.getMessage());
}
return "placeholder";
}
#GetMapping("/emitter")
public SseEmitter eventEmitter(#RequestParam String userId) {
emitter = new SseEmitter(-1L);
return emitter;
}
}
And our client code is as follows:
const eventSource = new EventSource('http://localhost:8080/emitter?userId=testUser');
eventSource.addEventListener("message", (event) => {
console.log(event);
});
eventSource.addEventListener("open", (event) => {
console.log("connection opened");
});
eventSource.addEventListener("error", (e) => {
if (e.readyState === EventSource.CLOSED) {
console.log('closed');
}
else {
console.log(e);
}
e.target.close();
});
document.getElementById("btn").onclick = e => {
fetch('http://localhost:8080/test').then( data => console.log(data)).catch(data => console.log(data));
};
Immediately, an error is created before we can click the button to generate an event.
What could be wrong?
What does your Spring boot terminal say? I think I need that information to address your program's error. By the way allowing cross origin resources sharing for requests from any sources (using wildcard) is a very very bad practice.
One possible reason of error is something's wrong when you create an instance of SSEemitter. (new SSeEmitter(-1L))
SSeEmitter(Long timeout) is creating server side event with set timeout it says. So if timeout is -1, I guess it would immediately be timed out and return timeout response. So it wouldn't be error, just working as written
i have a spring boot controller, and i'm trying to return to my frontend(i use angular cli) the response value (200,300,400,...) of a http post request, the problem is that when the post request fails my code does not return the status error, and i can't really understand why; i need the status of the request in the front end in order to show a toastr in case of success or errors
here is my front-end code:
postdipendenti(raw: any,comp:any,gr:any,fp:any){
var dip = '{' +'"id"'+':'+'0'+','+'"nome"'+':'+'"'+raw[0]+'"'+','+'"cognome"'+':'+'"'+raw[1]+'"'+','+'"data_nascita"'+':'+'"'+raw[2]+'"'+','+'"mail"'+':'+'"'+raw[3]+'"'+','+'"telefono"'+':'+raw[4]+','+'"setCompetenze"'+':'+JSON.stringify(comp)+',"listaGr":'+JSON.stringify(gr)+',"fp":'+JSON.stringify(fp) +'}'
const obj = JSON.parse(dip);
console.log("non json ->"+ dip)
var res=this.http.post<any>('http://localhost:8080/postdipendente_competenze', obj).subscribe(
(val) => {console.log("andata "+ JSON.stringify(val))
if(val == "200")
this.toastr.success("dipendente inserito correttamente","SUCCESSO");
},
(error) => { //Error callback
console.log('error caught in component '+error)
this.toastr.error("dipendente non inserito","ERRORE")
}
)
}
and here is my back-end:
#CrossOrigin(origins = "http://localhost:4200")
#PostMapping("postdipendente_competenze") // aggiunge un nuovo dipendente con competenze esistenti
public ResponseEntity<?> addDipendenteCompetenze(#RequestBody dipendenteRequest dipReq) {
try {
ds.addDipendenteCompetenze(dipReq);//function that does the post request
return ResponseEntity.status(HttpStatus.OK).body(200);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(409);
} catch (BadRequest e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(400);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(500);
}
}
what am i doing wrong? i'm stuck and i can't understand why. any help is welcome, thanks.
In my code I refer to an API using the following
fetch('https://?....).then(response => {
return response.json();
However I have a requirement to pass in a local file (JSON) instead of the api url as below
fetch('file:///E:/testData.json')
I get the error "URL scheme must be "http" or "https" for CORS request"
Would really appreciate if someone can point me the right direction here. How can I parse a local JSON in this case ? what am i doing wrong here
you need to create the folder with json file in your project and call in this mode:
fetch('./api/some.json')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
This is my controller
public IActionResult Privacy(int? id)
{
if(id.HasValue)
throw new Exception("privacy page exception");
return View(); ///working- redirected to Error view
}
[HttpGet]
public async Task<IActionResult> SearchCustomerPartial([FromQuery] CustomerSearch searchModel)
{
try {
var result = await _customerapiService.SearchCustomer(searchModel);
return PartialView("_CustomerList", result.Data);
}
catch ( Exception e)
{
return RedirectToAction("Index", "Error"); ---Not working it remains in same controller
}
}
Global exception handler
public static void UseGlobalExceptionHandler(this IApplicationBuilder app
, ILogger logger
, string errorPagePath
, bool respondWithJsonErrorDetails = false)
{
app.UseExceptionHandler(appBuilder =>
{
appBuilder.Run(async context =>
{
//============================================================
//Log Exception
//============================================================
var exception = context.Features.Get<IExceptionHandlerFeature>().Error;
string errorDetails = $#"{exception.Message}
{Environment.NewLine}
{exception.StackTrace}";
int statusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusCode = statusCode;
//Check status code, if different redirect error page
context.Response.Redirect(errorPagePath); --- Redirect code
await Task.CompletedTask;
});
});
}
Problem:
I have 2 Methods Privacy() and SearchCustomerPartial() in controller.
My global exception handler working fine for Privacy it redirect to Error view when error.
But not not working for SearchCustomerPartial() (returns partial view)
if any exceptions in the SearchCustomerPartial() not redirected to Error view and showing Error in same page and overlap.
Below is the Error page
How to redirect to Error page in the partial view returns in the controller .. Am using Asp.net core 3.1
Kindly suggest..
EDIT:
My javascript Code
fetch(url + "?" + o)
.then(response => response.text())
.then(html => {
debugger
// console.log(html);
document.getElementById('partialresult').innerHTML = html;
})
.catch(err => {
debugger
console.log("Can’t access " + url + " response. Blocked by browser?" + err)
document.getElementById('partialresult').innerHTML = "";
});
Server returns 500 But it not coming under Catch in javscript..Kindly suggest
if Bad Request come from server how to handle in javascript
if any exceptions in the SearchCustomerPartial() not redirected to Error view and showing Error in same page and overlap.
Based on your code and requirement, you can try to modify the code like below.
fetch(url + "?" + o)
.then(function (response) {
//check if it is redirected to custom error page
if (response.redirected && response.url.indexOf("/Home/Error1")>0) {
response.text().then(function (html) {
document.write(html);
});
} else {
response.text().then(function (html) {
document.getElementById('partialresult').innerHTML = html;
});
}
})
This is a strange problem and I tried to debug it through the day with no effect. I have written a REST API in Spring 4 and it seems to be working fine. I've tested the links with postman, they work fine and even when I test it on the browser it works fine. So my works like this, If a I make a call to,
http://localhost:9000/myapi/receivedMessags/myUserId
I get JSON of this form,
[{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"},{"senderId":"myUSerId","receiverId":"mySenderId","mediaId":"22797361348"}]
Which is perfectly valid JSON data.
Now I try to consume this data using the fetch-API. This is my function,
export function fetchMessages(url) {
return fetch(url, { method: "get",
headers: {
"Content-type": "text/plain"
},
credentials: 'include',
mode: 'no-cors'})
.then((response) => {
return response.json();//A
})
.then((data) => {
//console.log("data: ", data);
// let messages = [];
// for (let i = 0; i < data.length; i++) {
// let message = new Message(data[i].senderId, data[i].receiverId, data[i].mediaId);
// messages.push(message);
// }
console.log(data);
//return messages;
})
.catch((error)=> {
console.log("Request failed: ", error);
});
}
This method fails to access the data.
I fails with the error,
Request failed: SyntaxError: Unexpected end of input(…)
After a lot of debugging I figured out that there's nothing wrong with the syntax and it fails at line A where it tries to parse the response to json.
If I change that line to response.text() the syntax error goes away and I get blank, which means there's no data. My question is why am I not able to access the data, when I know my server code is working fine.
If it helps, here's the server code,
#RequestMapping(value = "/receivedMessages/{userId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity getReceivedMessages(#PathVariable("userId") String userId) {
List<Message> receivedList = null;
try {
receivedList = controller.getReceivedMessages(userId);
} catch (Exception e) {
}
return new ResponseEntity(receivedList, HttpStatus.OK);
}
Infact, I've tried to POST on the API as well(which works fine in POSTMAN) but fails using my front-end client.
Any help highly appreciated.