How to add a default cookie with Dio via CookieManager in dart - dart

Dio used to allow setting default cookies in baseOptions such as this.
final BaseOptions dioBaseOptions = BaseOptions(
baseUrl: 'http://192.168.1.19',
headers: {
"Host": "api.example.test",
"Content-Type": "application/json",
},
cookies: [
Cookie('XDEBUG_SESSION', 'PHPSTORM'),
],
);
With the updated API this appears to be no longer the case and we need to go with interceptors (or there's an alternative)? Trying to adjust the above code to the new Dio API I have the following except I cannot see how to add a cookie to the jar.
var dio = Dio();
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
var customHeaders = {
"Host": "api.example.test",
"Content-Type": "application/json",
};
options.headers.addAll(customHeaders);
return options;
}));
var cookieJar=CookieJar();
/// I was expecting something like .add(Cookie(...))
dio.interceptors.add(CookieManager(cookieJar));

Looks like the only way is to manually write the cookie in the headers
final BaseOptions dioBaseOptions = BaseOptions(
baseUrl: 'http://192.168.1.19',
headers: {
'Host': "api.radio.test",
'Content-Type': 'application/json',
'Cookie': 'XDEBUG_SESSION=PHPSTORM',
},
);

Related

Request with GET/HEAD method cannot have body APOLLO-CLIENT

I'm using docker network and try to use apollo-client, apollo-upload(createUploadLink) and I try to sent Barear token in headers too. the error show up Request with GET/HEAD method cannot have body
But if I change my url into real url [ not dockerNetwork everything work fine]
export const client = (req) => {
const uri = http://dockerNetwork:3000
return new ApolloClient({
link: authLink(req).concat(createUploadLink({
uri: uri ',
});),
cache: new InMemoryCache(),
});
};
const authLink = req => {
return setContext(_ => {
return {
headers: {
...req.headers,
authorization: `Bearer ${req.cookies.token)}`,
},
};
});
};
How can I fix this error by using docker network
Finally I found solution, first I use
"#apollo/client": "3.4.20"
"apollo-upload-client": "^16.0.0",
and I downgrade apollo/client to 3.3.20
"#apollo/client": "3.3.20",

Why doesn't my Zapier Integration Dynamic Field work?

I have a simple zapier integration built and it works perfectly. However, I'm adding dynamic fields. Again it all seems to work perfectly when I test the zap. My dynamic form fields appear just as I expected.
The problem is sending the value of those dynamic forms to my API. I am using the zapier console and when I configure the API request I am using the following:
Where body['custom_fields'] is supposed to send all my dynamic fields or even all of the fields. But when it hits my API custom_fields parameter is blank.
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: {
'email': bundle.inputData.email,
'custom_fields': bundle.inputData
/**
I've tried the following with no luck:
'custom_fields': bundle.inputData.fields
'custom_fields': bundle.inputData.undefined
'custom_fields': bundle.inputData
*/
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
Ok after a few days, it's the simplest answer.
Obviously an object can't be sent over params.
so instead of having
'custom_fields': bundle.inputData
I just add the whole object to the params and it takes care of all keys and values
params: bundle.inputData
Here is the full body
const options = {
url: 'https://apiendpoint.com',
method: 'POST',
headers: {
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
params: bundle.inputData,
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
You can use the spread operator ...bundle.inputData like explained in the doc:
https://platform.zapier.com/docs/input-designer#how-to-include-dynamic-fields-in-api-calls
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: { ...bundle.inputData }
}
You can even namespace your request data like that:
body: {
request: { ...bundle.inputData }
}
NB : the spread operator raises a syntax error in Zapier code editor, but it works.

Tampermonkey GM_xmlhttpRequest not sending Request properly

I am trying to implement a tampermonkey script that triggers an API call to a Jira instance to create a ticket with some information found in the page I am on (on a different domain).
Here's what I've tried:
async function createJiraTicket() {
let elements = await obtainThingsForCreatingJiraTicket();
let createJiraTicketUrl = `https://${jiraDomain}/rest/api/latest/issue`;
let requestDataForCreation =`
{
"fields": {
"project": { "key": "${elements.project}" },
"summary": "${elements.title}",
"description": "nothing",
"issuetype": {"name": "Issue" }
}
}`;
GM_xmlhttpRequest ( {
method: "POST",
url: `${http}://${createJiraTicketUrl}`,
user: 'user:pwd', // also tried user:'user', password:'pwd',
data: requestDataForCreation,
header: 'Accept: application/json',
dataType: 'json',
contentType: 'application/json',
onload: function (response) {
jiraTicketLog(`[Ajax] Response from Ajax call Received: `);
}
} );
However, when I run createJiraTicket(), I am getting the following error:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
at <anonymous>:1:7
I have established the correct #connect tags on the script, so I am pretty blind on where the problem may be...
Can someone help?
Thanks
So I came up with the answer to fix it, apparently it was a number of different details:
So,
Authorization had to be included onto the headers, coded on base64 and keyworded "Basic".
User-Agent needs to be overriden on headers, with any dummy string.
overrideMimeType needed to be set to json.
That all made the trick.
This was the working code.
let createJiraTicketUrl = `//${jiraDomain}/rest/api/latest/issue`;
let authentication = btoa('admin:foobar1');
GM.xmlHttpRequest({
method: "POST",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json",
"Authorization": `Basic ${authentication}`,
"User-Agent": "lolol"
},
url: `${http}:${createJiraTicketUrl}`,
data: JSON.stringify(requestDataForCreation),
dataType: 'json',
contentType: 'application/json',
overrideMimeType: 'application/json',
onload: function (response) {
let url = `${http}://${jiraDomain}/browse/${JSON.parse(response.response).key}`;
log(`${JSON.parse(response.response).key} ticket created: ${url}`);
openJiraTicket(url);
}

Flutter HTTP Post returns 415

I have an issue with using Method.Post on my flutter app using http dart library. It seems that when I tried to post data from my WebAPI it gaves me a StatusCode 415. See my code below:
Code Login:
Future<User> login(User user) async {
print(URLRequest.URL_LOGIN);
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: {
'username': user.username,
'password': user.password
}, headers: {
"Accept": "application/json",
}).then((dynamic res) {
print(res.toString());
});
}
Code NetworkUtils:
Future<dynamic> post(String url, {Map headers, body, encoding}) async {
return await http
.post(url, body: body, headers: headers, encoding: encoding)
.then((http.Response response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception('Error while fetching data.');
}
return _decoder.convert(res);
});
}
Does anyone knew whats going on my code?
Try adding this new header:
headers: {
"Accept": "application/json",
"content-type":"application/json"
}
UPDATE
Ok now you need to send json data, like this :
import 'dart:convert';
var body = jsonEncode( {
'username': user.username,
'password': user.password
});
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: body, headers: {
"Accept": "application/json",
"content-type": "application/json"
}).then((dynamic res) {
print(res.toString());
});
}
#Alvin Quezon
I met the same error as yours and fix it, please see below.
[Error]
StateError (Bad state: Cannot set the body fields of a Request with content-type "application/json".)
[Reason]
when you use the Flutter plug 'http.dart' method 'http.post()', you should read the document in detail below (note the black fonts):
Sends an HTTP POST request with the given headers and body to the given URL.
[body] sets the body of the request. It can be a [String], a [List<int>] or
a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
used as the body of the request. The content-type of the request will
default to "text/plain".
If [body] is a List, it's used as a list of bytes for the body of the
request.
If [body] is a Map, it's encoded as form fields using [encoding]. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
[encoding] defaults to [utf8].
For more fine-grained control over the request, use [Request] or
[StreamedRequest] instead.
Future<Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
[Solution]
So just encode your body as a string ,then you can set the header 'content-type' as 'application/json'.
see the codes of #diegoveloper answered!

Angular 2 urlencoded in http post

I try to consume a service via post whit angular2. This my code:
var m_dataRequest = this.buildLoginUserPasswordRequest(password, key);
let headers = new Headers({
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'es-ES,es;q=0.8,en;q=0.6',
'Content-Type': 'application/x-www-form-urlencoded',
});
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set("message", JSON.stringify(m_dataRequest));
body.set("webService", "authService");
return this.http
.post(this.Url, body.toString(), options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
private buildLoginUserPasswordRequest(password:string, key:string): any {
var m_dataRequest = {
"ser:nativeAppAuth": {
"-xmlns:ser": "http://services.mobileappbc.ws.todo1.com/",
"password": this.utilService.buidRSAPass(password, t1Assertion),
"key": key,
"deviceInfo": this.utilService.getDeviceInfo()
}
};
return m_dataRequest;
}
The Content-type is application/x-www-form-urlencoded because the backend need the info of this way.
My problem is the character ":" is not convert to equivalent urlencoded %3A+.
this cause a problem in my backend service.
any Suggestion for solve this?
Thanks!
Json.stringify does not uri encode data because it can handle it.
You need to use uriencode()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

Resources