//// I get a sucess response from first request in 2 seconds but still it waits for 30 seconds to hit second api
let request = AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
switch response.result {
case .success(let data):
print("data \(data)")
let url = URL(string: "https://apps.com/api/restid?user_id="+Constants().GETVALUE(keyname: USER_ID))!
AF.request(url).responseJSON { response_next in
print(response_next)
}
break
case .failure(let error) :
print("error \(error)")
}
}
Related
I have written a simple backend RESTAPI web app. I can get the vehicles routes to work but not if i try to reach these routes: File: web/Network/service.dart line 22
app.get('/vehicles/<id|.*>', (Request request, String id) {
or even something simple like this: File: web/Network/service.dart line 17
app.get('/hi/<name|.*>', (Request request, String name) async {
the / and /vehicles work. I have the code on github:
https://github.com/hassandaru/dart_middleware_example/blob/main/web/Network/service.dart
The issue bits are:
app.get('/hi/<name|.*>', (Request request, String name) async {
return await Response.ok('hello $name',headers: {'Content-Type': 'application/json' });
});
app.get('/vehicles/<id|.*>', (Request request, String id) {
final parseId = id.isNotEmpty ? id.toString() : '0';
var result = APICalls().fetchByID(parseId);
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
It matches everything in the documentation. Any suggestions would be greatly appreciated.
import '../dbsettings.dart' as db;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'dart:convert';
import 'apiCall.dart';
class Service {
Handler get handler {
var app = Router();
app.get('/', (Request request) {
return Response.ok('hello transport API', headers: {'Content-Type': 'application/json'});
});
app.get('/hi/<name|.*>', (Request request, String name) async {
return await Response.ok('hello $name',headers: {'Content-Type': 'application/json' });
});
app.get('/vehicles/<id|.*>', (Request request, String id) {
final parseId = id.isNotEmpty ? id.toString() : '0';
var result = APICalls().fetchByID(parseId);
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
//to read all entries of vehicle
app.get('/vehicles', (Request request) async {
var result = await APICalls().showAllVehicles();
//need to get result from result before sending it in json, find it j
// return Response.ok(json.encode(result), headers: {'Content-Type': 'application/json'});
return Response.ok(jsonEncode(result), headers: {'Content-Type': 'application/json'});
});
return app;
}
}
the postman give me a code it's first time to see the same, and it dont work with me here is the postman code
var headers = {
'Accept': 'application/json'
};
var request = http.MultipartRequest('POST', Uri.parse('https://***.com/api'));
request.fields.addAll({
'action[]': 'Auth',
'action[]': 'Login',
'mobile': '1234',
'password': '1234'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
its return "Internal Server Error", I tried to edit the code
if (response.statusCode == 200) {
var item =
JsonDecoder().convert("${await response.stream.bytesToString()}");
print("item $item");
return response.statusCode;
} else {
print("response.statusCode ${response.statusCode}");
print("response.reasonPhrase :=> ${response.reasonPhrase}");
return response.statusCode;
}
and it print
I/flutter (28103): response.statusCode 500
I/flutter (28103): response.reasonPhrase :=> Internal Server Error
I contact the server programers and they told me the server work well and the website reseave the data well, please help
It's stopped working for the last 5 days before that it's working fine.
now when we call this end point in mobile then return 429 and redirect to the Instagram login page.
I had the same problem and I've fixed it by changing the User-Agent to Mozilla/5.0 in the request's header.
Here is what I did on iOS (Swift):
let url = URL(string: "https://www.instagram.com/spacex/?__a=1")
let request = NSMutableURLRequest(url: url)
request.setValue("Mozilla/5.0", forHTTPHeaderField: "User-Agent")
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
DispatchQueue.global(qos: .background).async {
let requestData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let error = error {
print("Error # loadInstagram(): \(String(describing: error))")
return
}
if let data = data {
self.processInstagram(data: data) // function for processing the json data received
} else {
print("Error - missing data # loadInstagram()")
}
}
requestData.resume()
}
I was trying to make an API call to another domain, which has no-cors enabled.
The API call was made something like this:
let url = `https:sampleApiUrl?params=xxxx`;
console.log("hitting dashboard url")
get(url, token)
.then((resp) => {
console.log("resp", resp)
})
.catch((error) => {
console.log(error)
})
This API call, subsequently calls a 'get' method:
const get = (url, authToken) => {
return baseFetch(url, 'get', false, authToken).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
});
}
Now, this get method calls a baseFetch method:
const baseFetch = (url, verb, body, authToken) => {
const request = {
method: verb,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'credentials': 'include'
},
mode: 'cors'
}
if (authToken){
// adding x-access-token in the request header
request.headers['x-access-token'] = authToken;
}
if (body){
request.body = JSON.stringify(body);
}
return fetch(url, request);
}
Now, when this API call is requested, I can't see the "x-access-token" populated in the browser network call.
No x-access-token in request-headers
Also, I am not sure why I get status code 204 in response.
Calling this API from postman and directly from browser or calling as a curl request, returns the correct response.
Thanks
Looking at the image, you are looking at the headers for pre flight OPTIONS method and not the GET method. The pre flght request is generated by the browser and it never has any custom header. therefore it did not have the x-access-token in its headers.
If this is my request, how do I see the response's text in the debugger window, in particular when there's an error?
let request = Alamofire.request(
webServiceUrl + url, method: method, parameters: parameters)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
request.responseJSON { response in ... }
In my response handler, I added...
if let resp = response.data {
NSLog("Server Response: \(NSString(data: resp, encoding: String.Encoding.utf8.rawValue))")
}