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

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)

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?

How to stop Ember CLI's http-mock server throwing an error when there are websockets in one of the server files?

I have a websocket in one of my http-mock server files initialised as follows:
var WebSocketServer = require('ws').Server;
var socketServer = new WebSocketServer({port: 13434, path: "/update"});
and later in the file I have the following happen on connection:
socketServer.on('connection', function(ws) {
ws.on('close', function(message) {
clearInterval(sendResults);
});
ws.on('message', function(message) {
handleClientMessage(ws, message);
});
sendResults = setInterval(function() {
ws.send(JSON.stringify(getResultsFromEntries()));
}, resultInterval);
});
However, whenever I edit any of the server files I get the following error:
File changed: "mocks/entry.js"
Just getting started with Ember? Please visit http://localhost:4200/ember-getting-started to get going
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE 0.0.0.0:13434
at Object.exports._errnoException (util.js:907:11)
at exports._exceptionWithHostPort (util.js:930:20)
at Server._listen2 (net.js:1250:14)
at listen (net.js:1286:10)
at net.js:1395:9
at nextTickCallbackWith3Args (node.js:453:9)
at process._tickCallback (node.js:359:17)
I'm guessing I need to detect when the file change happens and close the current websocket connection. On process exit doesn't seem to get called until the server dies, and then process.on('exit', function() {}) is called the number of times the server has refreshed. It doesn't bother me too much as I have a script that restarts ember server if it goes down, but other developers don't like the ember server going down when they edit a server file. Any ideas?
I ended up setting a new WebSocketServer as a property of process (which persists over the server getting restarted) then at the top of the file I close the previous WebSocketServer (if there was one):
if (process["updateSocketServer"]) {
process["updateSocketServer"].close();
process["updateSocketServer"] = undefined;
}
Then setup a new WebSocketServer:
process["updateSocketServer"] = new WebSocketServer({port: 13434, path: "/update"});
Then I did the following on connection:
process["updateSocketServer"].on('connection', function(ws) {
// Connection code.
});
Should you be closing/terminating the connection on close?

Angular 2 http get not working, never reaches the server

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

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.