Error FormatException received when api callled on localhost "127.0.0.1/app/sanjhapizza/lib/userLogin.php" in flutter - flutter-dependencies

**this is my code which contains API call code.The following error rceived while executing this code:
Exception:FormatException: //127.0.0.1/app/sanjhapizza/lib/userLogin
Api result:failed
Error: Assertion failed:
Please help me
import 'dart:convert';
import "package:http/http.dart" as http;
Future<String> userLogin(String userid) async {
try {
String ulink = "http://127.0.0.1/app/sanjhapizza/lib/userLogin.php";
final response = await http.post(Uri.http(ulink),
body: {"userid": userid});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
} on Exception catch (e) {
print("Exception:$e");
return ("failed");
}
}

Related

Axios does not catch any of the error responses in vue

I have a function created that makes an axios get API call. When the api responds successfully everything works fine, but when the API call has any kind of error it does not reach the catch block. For example:
public async getData() {
try {
const response = await axios.get('https://599d6a620a785b0011f4f6c8.mockapi.io/users');
console.log('success', response)
}catch( error) {
console.log('errr',error);
};
}
I get the following response in the console:
success {data: Array(100), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
Now, when i change the url of the above function (to mimic a 404) to:
public async getData() {
try {
const response = await axios.get('https://599d6a620a785b0011f4f6c8.mockapi.io/toReturn404');
console.log('success', response)
}catch( error) {
console.log('errr',error);
};
}
I get the following responses
Even though it should have been thrown to the catch block it stays in the try block.
I tried recreating it in the stackblitz but it works as expected there : Stackblitz
Axios version in both stackblitz and the project is : "axios": "^0.27.2",

problem in making http.get() request in flutter

i am learing about api's and http request in flutter and i am facing problem in making a get request as in any tutorial they are directly pasting string url inside get as parameter but when i post it as string it is showing error: The argument type 'String' can't be assigned to the parameter type 'Uri'.
can any one help me in this :
this is my sample code :
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
// This example uses the Google Books API to search for books about http.
// https://developers.google.com/books/docs/overview
var url = 'https://www.googleapis.com/books/v1/volumes?q={http}';
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url); // i am getting error here
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
here is image of my code with error
enter image description here
first import http as http
import 'package:http/http.dart' as http;
then parse your link to Uri using
var url = Uri.parse('https://www.googleapis.com/books/v1/volumes?q={http}');
http.Response response = await http.get(url);
try {
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
} else {
return 'failed';
}
} catch (e) {
return 'failed';
}
If still doesn't work try this:
import 'package:http/http.dart';
var response = get(Uri.parse('https://www.google.com'));
Try this (Add http to pubspec.yaml under dependencies):
import 'package:http/http.dart' as http;
var response = http.get(Uri.parse('https://www.google.com'));
You passing string the error says need an uri so create an uri and use in it.
var uri = new Uri.http("example.org", "/path", { "q" : "{http}" });
First of all, check your pubspec.yaml file and HTTP version. It should be the actual one you can find here: https://pub.dev/packages/http/install
For example, it is:
http: ^0.12.2
at the moment
Here is my code and it works well:
main.dart
import 'package:flutter/material.dart';
import 'package:stackowerflow/my_app.dart';
void main() {
runApp(MyApp());
}
my_app.dart
import 'dart:convert' as convert;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class MyApp extends StatelessWidget {
Future<void> stackHelp() async {
var url = 'https://www.googleapis.com/books/v1/volumes?q={http}';
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView '),
),
body: Container(
child: TextButton(onPressed: stackHelp, child: Text('Push me')),
),
),
);
}
}
RESULT
flutter: Number of books about http: 485.

How do I return an error from a Controller in Loopback 4?

I have a controller method
// ... inside a controller class
#get('/error', {})
async error() {
throw new Error("This is the error text");
}
The response I'm getting from this error front-end is:
{
"error": {
"statusCode": 500,
"message": "Internal Server Error"
}
}
What I would like the error to be is:
{
"error": {
"statusCode": 500,
"message": "This is the error text"
}
}
How do I return an error from a controller in Loopback 4?
Hello from the LoopBack team 👋
In your controller or repository, you should throw the Error exactly as shown in your question.
Now when LoopBack catches an error, it invokes reject action to handle it. The built-in implementation of reject logs a message via console.error and returns an HTTP response with 4xx/5xx error code and response body describing the error.
By default, LoopBack hides the actual error messages in HTTP responses. This is a security measure preventing the server from leaking potentially sensitive data (paths to files that could not be opened, IP addresses of backend service that could not be reached).
Under the hood, we use strong-error-handler to convert Error objects to HTTP responses. This module offers two modes:
Production mode (the default): 5xx errors don't include any additional information, 4xx errors include partial information.
Debug mode (debug: true): all error details are included on the response, including a full stack trace.
The debug mode can be enabled by adding the following line to your Application constructor:
this.bind(RestBindings.ERROR_WRITER_OPTIONS).to({debug: true});
Learn more in our docs: Sequence >> Handling errors
Alternatively, you can implement your own error handler and bind it as the sequence action reject. See Customizing sequence actions in our docs.
export class MyRejectProvider implements Provider<Reject> {
constructor(
#inject(RestBindings.SequenceActions.LOG_ERROR)
protected logError: LogError,
#inject(RestBindings.ERROR_WRITER_OPTIONS, {optional: true})
protected errorWriterOptions?: ErrorWriterOptions,
) {}
value(): Reject {
return (context, error) => this.action(context, error);
}
action({request, response}: HandlerContext, error: Error) {
const err = <HttpError>error;
const statusCode = err.statusCode || err.status || 500;
const body = // convert err to plain data object
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body), 'utf-8');
this.logError(error, statusCode, request);
}
}
If you just want to show error message, you just extend Error object and throw it like below. (Loopback documentation didn't mention this anyway)
Avoid using 5xx error and use 4xx error to show some important thing to user is best practice and so that Loopback4 was implemented like this.
class NotFound extends Error {
statusCode: number
constructor(message: string) {
super(message)
this.statusCode = 404
}
}
...
if (!await this.userRepository.exists(id)) {
throw new NotFound('user not found')
}
For my situation, I found a catch in my sequence.ts file. Inside the catch, it checked if the error had a status code of 4xx, and if not, it just returned a anonymous 500.
Here's the code I was looking for to do the logic:
// sequence.ts
...
} catch (err) {
console.log(err);
let code: string = (err.code || 500).toString();
if (code.length && code[0] === '4') {
response.status(Number(code) || 500);
return this.send(response, {
error: {
message: err.message,
name: err.name || 'UnknownError',
statusCode: code
}
});
}
return this.reject(context, err);
}
...
Here's how you tell it what to do:
// ... inside a controller class
#get('/error', {})
async error() {
throw {
code: 400,
message: "This is the error text",
name: "IntentionalError"
}
}
To throw custom validation error I use this method:
private static createError(msg: string, name?: string): HttpErrors.HttpError {
const error = new HttpErrors['422'](msg);
error.name = name ?? this.name;
return error;
}
Catch error examples here are for defaultSequence, overriding the handle method.
But nowdays app template uses MiddlewareSequence.
So here is the example, how tomodify the response in middleware sequence, you can use this example:
import { Middleware, MiddlewareContext } from '#loopback/rest';
export const ErrorMiddleware: Middleware = async (middlewareCtx: MiddlewareContext, next) => {
// const {response} = middlewareCtx;
try {
// Proceed with next middleware
return await next();
} catch (err) {
// Catch errors from downstream middleware
// How to catch specific error and how to send custom error response:
if (HttpErrors.isHttpError(err) || (err as HttpErrors.HttpError).statusCode) {
const code: string = (err.statusCode || 500).toString();
if (code.length && code[0] === '4') {
response.status(Number(code) || 500);
return response.send({
error: {
message: err.message,
name: err.name || 'UnknownError',
statusCode: code
}
});
}
}
throw err;
}
};
And register the middleware in application.ts
this.middleware(ErrorMiddleware);

Unable to get error message from API Angular 6

I use the following function to Post a object of a given class.
public Post<T>(object: T, url: string, httpOptions: {}): Observable<T> {
return this.httpClient.post<T>(`${environment.apiEndpoint}` + url, object, httpOptions)
.pipe(
catchError(this.handleError)
);
}
This function is called in all the service that wants to post something. Like this.
public addEquipment(equipment: Equipment): Observable<Equipment> {
return this.shared.Post<Equipment>(equipment, this.url, this.header);
}
addEquipment is then executed within the component that uses that service. Like this.
this.equipmentService.addEquipment(result)
.subscribe((data: any) => { this.alertService.success(data) }, (error: any) => this.alertService.error(error));
The problem is when the API returns a error (that I can see includes a error message, in the network tab) it tells me that there is no body in the response. The API returns a HttpResult where the error message is added to the response field.
return new HttpResult { StatusCode = HttpStatusCode.Conflict, Response = "Error message"}
I use the following function to handle the errors.
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
}
else {
console.log(error);
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
console.log(error);
return throwError(
error.error)
};
It is Angular 6 and a ServiceStack API.
All suggestions would be appreciated.
FYI it's preferable to return structured error responses in ServiceStack which you can do with:
HttpError.Conflict("Error message");
Which will let you catch it when using ServiceStack's TypeScript ServiceClient with:
try {
var response = await client.post(request);
} catch (e) {
console.log(e.responseStatus.message);
}
But from this answer for handling errors with Angular HTTP Client it suggests the error body should be accessible with:
this.httpClient
.get("data-url")
.catch((err: HttpErrorResponse) => {
// simple logging, but you can do a lot more, see below
console.error('An error occurred:', err.error);
});

axios.post is returning error when used with redux-saga

I recently converted my redux-thunk middleware code to use redux-saga and it was working all these days fine and all of a sudden it is throwing an error. Not sure why!!
My Spring Boot REST Client is returning the proper response and no errors in the log. And if i make the same request using swagger i am getting the response back as expected so there is nothing wrong on the server side.
I have the following code
const LOGIN_URL = 'http://localhost:8888/api/a/login';
export function* loginUserAsync(action) {
console.log('.loginUserAsync() : action:', action);
yield put({ type: LoginConstants.LOGIN_USER_IN_PROGRESS });
const postParams = {
username: action.props.username,
password: action.props.password
};
const headerParams = {
headers: {
'Content-Type': 'application/json',
//'Content-Type': 'x-www-form-urlencoded'
}
};
console.log('headerParams', headerParams);
console.log('postParams', postParams);
try {
console.log('Before making async post call using axios');
const response = yield call(axios.post, LOGIN_URL, postParams, headerParams);
let token;
console.log('response', response);
if (response.headers) {
token = response.headers['x-auth-token'];
AsyncStorage.setItem('jwt', token);
}
// Login Succeeded fire Login Success Action
yield put({
type: LoginConstants.LOGIN_USER_SUCCESS,
token,
account: response.data
});
const navigatorUID = Store.getState().navigation.currentNavigatorUID;
Store.dispatch(NavigationActions.push(navigatorUID, Router.getRoute('home')));
} catch (error) {
// Login Failed fire Login Failure Action
console.log('loginUserAync() : error:[' + JSON.stringify(error) + ']');
yield put({
type: LoginConstants.LOGIN_USER_FAILURE,
error: error.data
});
}
}
export function* loginUser() {
console.log('.loginUser() :');
yield takeEvery(LoginConstants.LOGIN_USER, loginUserAsync);
}
In the console i am seeing the following:
I have no idea why it stopped working all of a sudden.
Thanks
Sateesh
For some reason localhost and 127.0.0.1 are not being recognized and i have to use the actual IP Address.
I had that Issue when i tried to run it in my mac book. It always worked with localhost in Ubuntu.