Angular 2 http get not working, never reaches the server - web-services

I am using a working project of Angular 2 from a Pluralsight course as a reference to make my first app.
This exisiting app fetchs the data from a Json file.
private _productUrl = 'api/products/products.json';
constructor(private _http: Http) { }
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
If I modify the url to my own web service that runs locally "http://localhost:53785/api/Session" and run the angular 2 app, It never reaches the breakpoint that I set in my web service and I get "SyntaxError: Unexpected end of JSON input" error.
In the console I get:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
Response
_body
:
""
headers
:
Headers
ok
:
false
status
:
500
statusText
:
"Internal Server Error"
type
:
2
url
:
"http://localhost:53785/api/Session"
proto
:
Body
Does anyone know why cant I reach my web service?
Thanks

Related

Get custom Error message from backend API and access on frontend

I am working on an Angular 9 project with a Flask backend server. In some of my API's there are multiple checks and areas where it can fail and I want to return custom messages to the frontend but I can't seem to access the error message.
As an example, if this was a basic route:
#app.route('/api/test/<int:test_id>/', method=['PUT', 'OPTIONS])
def test_route(test_id):
if test_id < 0:
abort(400, f'Custom Error Message')
else:
#Query data base, update something, return updated entry...
And this was my service function on the frontend (API_URL refers to the root url for the backend):
callTestRoute(id: number): Observable<any> {
const url = `${API_URL}/test/id/`;
return this.http.put(url, httpOptions);
}
And in my component where I call the service function:
updateEntry(id:number) {
this.db_api.callTestRoute(id).subscribe( success => {
console.log(success);
}, (error: HttpErrorResponse) => {
console.log("API ERROR RESP: ", error);
}
}
In the console, my logged message above outputs
"API ERROR RESP: Error Code: 400
Message: Https failure response for http://slate:3660/test/66/: 400 BAD REQUEST"
however, the network request response shows my custom error message. I cannot access this message within my angular component.
I have tried using jsonify() to return the error in my API like:
return jsonify({'errMsg': "Custom error message"}), 400
but I can still not access the error message, when I try to access error.error or any fields, they all show undefined. How do I return a custom message for failed API requests and how do I access those messages on the frontend?

FormatException: SyntaxError: Unexpected token < in JSON at position 1 in Flutter after changing proxy from HTTP to HTTPS

I have a project, backend with Django and frontend with Flutter framework. The project was working fine until I changed the proxy in my Nginx from HTTP to HTTPS. Still working in most cases without any Problem. just in some cases, where I have no Data in my Data Table, I want/have to return an empty list from the backend, I got an error:
GET https://servername/project-name/api/commitments/?email=emailaddress%40companyname.de&jahr=2022&kunde=adac-ev 500
FormatException: SyntaxError: Unexpected token < in JSON at position 1
code in flutter:
var uri = (APIPROTOCOL == 'http://')
? Uri.http(APIHOST, '/api/commitments/', uriQuery)
: Uri.https(APIHOST, '$APIHOST_PREFIX/api/commitments/', uriQuery);
try {
final response = await http.get(
uri,
headers: {"Authorization": "Bearer $authToken"},
);
And this is working on localhost and on a server with HTTP but the problem is only on a sever with HTTPS,
any idea? how can debug the code on the server? or how can I change my localhost from http:://localhost:protNumber/ to something like https://servername/project-name/. Any idea that could help me to debug the code with https?

Send array string with post httpClient ionic

I want to send params and recive another ones, and I got an issue with my method to sending these parametres (array of string and string) with post method of HttpClient in ionic.
The error (isn't the CORS Security, cause i run with my device too and i got the same issue):
Failed to load resource: the server responded with a status of 404 (Not Found).
Access to XMLHttpRequest at 'http://localhost:64411/getLabels' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My code from ionic:
var apiURL = 'http://localhost:64411/';
pathGetLabels: string = apiURL + 'getLabels';
constructor(public http: HttpClient, public material: MaterialProvider, public hp : Http) {
}
loadLabels(lbls: any){
return this.http.post(this.pathGetLabels, lbls ,Language);}
The array got no problems and this is:
Array(6)
0: "USER"
1: "Password"
2: "SaveAccount"
3: "lbl_login"
4: "ForgetPass"
5: "Register"
length: 6
And the code of Web Service Api Rest:
[Route("getLabels/{paramOne}/{paramTwo}")]
public HttpResponseMessage getLabels([FromBody]string[] paramOne, string idL)
{
var labels = LanguagesRepository.GetLabels(paramOne, idL);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, labels);
return response;
}
I tried to do these things to and I got the same issue:
return this.http.get(this.pathGetLabels+ JSON.stringify(lbls) +"/"+Language);
return this.http.get(this.pathGetLabels+ JSON.stringify(lbls), Language);

server responded with a status of 404 (Not Found): mean stack & ionic

I making a request to the back-end server of the port number 8000. I'm making request from the android emulator. so, instead of localhost i'm using ip address. It is throwing the error as
Failed to load resource: the
http://192.168.0.102:8000/api/facebookuser server responded with a
status of 404 (Not Found)
This is my code
postFacebookData(userdata) {
alert(userdata);
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://192.168.0.102:8000/api/facebookuser',userdata,{headers: headers})
}
This is from routes file
router.post('/facebookuser', function(req,res) {
console.log('facebook request');
It is not subscribing to the method
this.fbPage.postFacebookData(userData)
.subscribe((data: any) => {
if (data.success) {
alert('Data added sucessfully ' && data.msg);
this.authservices.storeUserData(data.token,data.user);
this.navCtrl.push(EditinfoPage);
}
else {
alert('data is not added');
}
},(err) => {
alert('error in subscribing ' + err);
I'm getting an error message in the cosole from the above code as
error in subscribing [object object]
The error is indicating, that the request cannot find the resource you are trying to request.
Make sure that the IP-Adress for your backend is correct (using ipconfig for instance)
Make sure that the endpoint "api/facebookuser" is correct
Make sure that the EMULATOR is in the same network (e.g. WLAN) than your computer (assuming that the backend is running on localhost)

Call HTTP (non SSL/HTTPS) REST from Firebase hosted site, using XMLHttpResponse

I am trying to build a Firebase hosted page that will connect to a (Django) HTTP web service using XMLHttpRequest in the below script.
<script>
function UserAction() {
var req = createRequest(); // defined below
// Create the callback functions:
var handleResponse = function (status, response) {
alert("status " + status + " response: " + response)
}
var handleStateChange = function () {
switch (req.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
alert("case 4" + req.responseType);
handleResponse(req.status, req.responseJson);
break;
default: alert("error");
}
}
req.onreadystatechange = handleStateChange;
req.open("GET", "https://foo.org:/bar/getid/?Id=" + document.getElementById('ID').value, true);
req.send();
function createRequest() {
var result = null;
if (window.XMLHttpRequest) {
// FireFox, Safari, etc.
result = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// MSIE
window.alert("windows");
result = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
// No known mechanism -- consider aborting the application
window.alert("no known mechanism");
}
return result;
}
}</script>
Using Chrome FireBase throws 404 error. Django server does not register any connection.
Using FireFox FireBase throws 404 error. But Django server throws
'code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\xcc\x01\x00\x00\xc8\x03\x03\xdf\x04{\x9f\xe4\xb2\xc2ij\x8d\x14\xd5\xaa\xdcu\x14+&\xa4\xa1\xdf\xdc\xd8\x9b?\xea\xbdh\xb8')`
I did find this in the FireBase documentation here, making me think this is not possible. But hopefully I am wrong, or there is a way to do this in development/test, but not production.
SSL only: Firebase Hosting is SSL-only, meaning that content will only
be served over HTTPS. As you are developing your application make sure
that all external resources not hosted on Firebase Hosting are loaded
over SSL (HTTPS), including any external scripts. Most browsers do not
allow users to load "mixed content" (SSL and non-SSL traffic).
thanks