I am trying to pass token and username which I pass from login screen using sharedPreference in data, my api is working properly on postman it response successfully according to my requirement but it's still giving me Error on response.data.
here is my update code
Dio dio=new Dio();
var data={
'username': getname,
'token': getaccesstoken
};
await dio
.post(localhostUrlTimeIn,data: json.encode(data))
.then((onResponse) async {
print(onResponse.headers);
print(onResponse.statusCode);
print(onResponse.data);
}).catchError((onerror){
print(onerror.toString());
//showAlertDialog(context);
});
here are the logs
I/flutter (17731): 1
I/flutter (17731): x-powered-by: Express
I/flutter (17731): connection: keep-alive
I/flutter (17731): keep-alive: timeout=5
I/flutter (17731): date: Wed, 09 Jun 2021 21:07:41 GMT
I/flutter (17731): content-length: 7
I/flutter (17731): etag: W/"7-Vuu5vA8hV5HSudFEr8bWQajjaE0"
I/flutter (17731): content-type: application/json; charset=utf-8
I/flutter (17731): 200
I/flutter (17731): Error
----------------------------------UPDATED ------------------------
here is the backend code
TimeIn=(req,res)=>{
jwt.verify(req.body.token, 'secret' , function(err, decoded) {
if (err)
{
err["expiredAt"] = err["expiredAt"].toLocaleString();
res.status(300).json(err)
}else{
let today = new Date()
Today = today.toLocaleString();
var date = Today.split(",")
var document = new User();
User.find({"username":req.body.username},function(err,data){
var dat = date[0];
var da = dateformat(dat,"yyyy-mm-dd")
console.log(da);
document.username= data[0].username;
document.Date = da;
document.TimeIn = date[1];
document.TimeOut = "";
document.manager_id= data[0].manager_id,
document.code = data[0].code
document.save();
console.log(document);
var token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: "30 minute"})
res.status(200).json({auth: true, AccessToken: token})
})
}
})
}
and here i call above method in app.js file
const TimeIn = require('./routes/TimeInTimeOut')
app.post("/TimeIn",checkToken,function(req,res){
console.log("api hit")
TimeIn.TimeIn(req,res)
})
and here is where i am checking token,which is created in app.js file!!
function checkToken(req,res,result){
const header= req.body.token;
if(typeof header !== 'undefined'){
const bearer =header.split('.');
const token = bearer[1]
//console.log(token)
req.token = token
//next();
result();
}else
res.json("Error")
}
i am getting now this error in frontend
DioError [DioErrorType.response]: Http status error [300]
here is the postman output
and here is the backend output
Please help me, i have tried it too much but still getting error.
Your response is fully working. You do get data back and a 200 status code. This means the request was a succes. You are assigning error to the data in the request serverside. The issue isn't in your request in the client.
// headers
I/flutter (17731): 1
I/flutter (17731): x-powered-by: Express
I/flutter (17731): connection: keep-alive
I/flutter (17731): keep-alive: timeout=5
I/flutter (17731): date: Wed, 09 Jun 2021 21:07:41 GMT
I/flutter (17731): content-length: 7
I/flutter (17731): etag: W/"7-Vuu5vA8hV5HSudFEr8bWQajjaE0"
I/flutter (17731): content-type: application/json; charset=utf-8
//Statuscode
I/flutter (17731): 200
//data
I/flutter (17731): Error
Related
I am trying to make a REST API call from my .Net MAUI mobile app.
First I log in, and get a JwtSecurityToken:
JwtSecurityToken JwtToken = new JwtSecurityToken(authenticationResult.IdToken);
Then I try to use it to make a REST API call:
HttpClient client = new ();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JwtToken.RawData);
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
This gives me an exception
Response status code does not indicate success: 401 (Unauthorized).
What is wrong or missing here?
ADDED:
Here is the respose:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: 162ea393-a9b2-4e6b-9786-d6e18d18afb1
Date: Sun, 25 Dec 2022 20:42:26 GMT
request-id: 162ea393-a9b2-4e6b-9786-d6e18d18afb1
Strict-Transport-Security: max-age=31536000
Transfer-Encoding: chunked
Vary: Accept-Encoding
WWW-Authenticate: Bearer realm="", authorization_uri="https://login.microsoftonline.com/common/oauth2/authorize", client_id="00000003-0000-0000-c000-000000000000"
X-Android-Received-Millis: 1672000947348
X-Android-Response-Source: NETWORK 401
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1672000947271
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Central US","Slice":"E","Ring":"3","ScaleUnit":"005","RoleInstance":"CH01EPF000051D6"}}
Content-Type: application/json
}, Trailing Headers:
{
}}
If you are developing your own API, you can then set this flag to true:
.AddJwtBearer(options =>
{
options.IncludeErrorDetails = true;
...
Then you will see a reason in the response why it failed:
HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
When I use http package by passing bear token to the http request it works but not with Dio package. What I am doing wrong?
Dio _dio = Dio(BaseOptions(
baseUrl: baseUrl,
connectTimeout: 5000,
receiveTimeout: 100000,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization' : 'Bearer$bearToken'
}
)
);
FlutterSecureStorage storage = FlutterSecureStorage();
Future<String>get bearToken async{
return await storage.read(key: 'key').then((value) => value.toString());
}
log :
I/flutter ( 4648): Dio error!
I/flutter ( 4648): STATUS: 401
I/flutter ( 4648): DATA: {status: failed, error: Unauthenticated, code: 401}
I/flutter ( 4648): HEADERS: connection: close
I/flutter ( 4648): x-powered-by: PHP/8.0.7
I/flutter ( 4648): cache-control: no-cache, private
I/flutter ( 4648): date: Wed, 11 Aug 2021 12:58:29 GMT
I/flutter ( 4648): access-control-allow-origin: *
I/flutter ( 4648): host: 10.0.2.2:8000
I/flutter ( 4648): content-type: application/json
Firstly, u get the token asynchronously, so u need to await the result and store it to a variable.
Like this final token = await bearToken;
Secondly, add the space before token value. 'Bearer $bearToken'
I have a Dio client with an interceptor attached, but when I try to add some headers, they don't appear in logs.
his is my code
Dio dio(KeyStore keyStore) {
final Dio dio = Dio(BaseOptions(
contentType: 'application/json',
connectTimeout: 5000,
sendTimeout: 5000,
));
final Dio tokenDio = Dio();
tokenDio.interceptors.add(LogInterceptor(responseBody: true));
dio.interceptors.add(LogInterceptor(responseBody: true));
dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) async {
final accessToken = await keyStore.readAccessToken();
final branchId = keyStore.readBranchId();
dio.lock();
options.headers[HttpHeaders.authorizationHeader] = 'Bearer: $accessToken';
options.headers['x-tenant'] = branchId;
handler.next(options);
dio.unlock();
}));
return dio;
}
Request headers...
I/flutter ( 8872): *** Request ***
I/flutter ( 8872): uri: https://api.someapi.com/users/058c026a-2dce-47e7-9fe1-61dec507265f
I/flutter ( 8872): method: GET
I/flutter ( 8872): responseType: ResponseType.json
I/flutter ( 8872): followRedirects: true
I/flutter ( 8872): connectTimeout: 5000
I/flutter ( 8872): sendTimeout: 5000
I/flutter ( 8872): receiveTimeout: 0
I/flutter ( 8872): receiveDataWhenStatusError: true
I/flutter ( 8872): extra: {}
I/flutter ( 8872): headers:
I/flutter ( 8872):
Dio interceptors are run in order. Since your auth interceptor is added after the log interceptor, LogInterceptor is called first, before the auth interceptor has a chance to add headers. The interceptor code looks fine to me, so I suspect that the authorization headers are correctly sent to the remote server.
To make your logs reflect the headers added by the auth interceptor, make sure LogInterceptor is the last element of the list dio.interceptors.
You don't necessarily need to use an interceptor.
You can update the default options like this:
dio.options.headers = {
HttpHeaders.authorizationHeader: 'Bearer: $accessToken',
'x-tenant': branchId
}
Then subsequent requests will use these values by default.
in my mobile application i'm using Chopper http library and i would like to cache http response with this library, my server return this headers with responses:
<-- 200 http://www.www.www/api/v1/dashboard/allData
content-type: application/json
cache-control: max-age=600, private
transfer-encoding: chunked
date: Mon, 07 Sep 2020 05:47:00 GMT
server: Apache
i added this interceptor to chopper interceptors:
final client = ChopperClient(
client: http.IOClient(
HttpClient()..connectionTimeout = const Duration(seconds: 60),
),
baseUrl: webUri,
services: [
_$WebApi(),
],
converter: const JsonConverter(),
interceptors: [
const HeadersInterceptor({'Content-Type': 'application/json','Cache-Control':'private, max-age=600'}),
HttpLoggingInterceptor(),
]);
now i expect cache work fine for my application, this solution is correct?
I want to post a status update to a Facebook Group using Node.js. It seems Node.js doesn't send the header…
var https = require('https');
var options = {
host: 'graph.facebook.com',
port: 443,
path: '/'+group_id+'/feed?access_token='+access_token,
method: 'POST',
headers: { 'message': text }
};
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
This is the log data:
statusCode: 400
headers: { 'cache-control': 'no-store',
'content-type': 'text/javascript; charset=UTF-8',
expires: 'Sat, 01 Jan 2000 00:00:00 GMT',
p3p: 'CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p"',
pragma: 'no-cache',
'www-authenticate': 'OAuth "Facebook Platform" "invalid_request" "(#100) A post to a group must have at least a message or attachment"',
'x-fb-rev': '443252',
'set-cookie': [ 'datr=removed; expires=Tue, 17-Sep-2013 12:18:08 GMT; path=/; domain=.facebook.com; httponly' ],
'x-fb-server': '10.62.5.40',
connection: 'close',
date: 'Sun, 18 Sep 2011 12:18:08 GMT',
'content-length': '115' }
{"error":{"message":"(#100) A post to a group must have at least a message or attachment","type":"OAuthException"}}
I think you need to send the message (the contents of your variable called 'text') in the body of your request, not the head. See this answer for an example of how to do this.