Making http Post request on Gupshup IDE works? - http

I copied gupshup's document code and modified just url as "http://posttestserver.com/post.php" and it doesn't work.
Anyone has an advice for me?
else if(event.message.toLowerCase() == "post") {
var contextParam = {
"User": {
"userName": "sbCobxxxx",
"Password": "xxxxxxx-9f-4307-9d9a-451f3xxxx075",
"Pin": "16776"
}
};
var url = "http://posttestserver.com/post.php";
var param = JSON.stringify(contextParam);
var header = {"Content-Type": "application/json"};
context.simplehttp.makePost(url, param, header);
}
function HttpResponseHandler(context, event) {
// if(event.geturl === "http://ip-api.com/json")
context.sendResponse(event.getresp);
}
Response returns empty string: ""
Thanks in advance.

Are you testing using Gupshup's emulator? If yes then POST and GET calls with headers and params doesn't work in the emulator as of now. The documentations mentions it. However, you can deploy the code and test it out using Gupshup proxy bot on Facebook messenger and it will work fine.
Here is a screenshot of the testing I did after directly copying your code into the IDE.

Related

Ionic 6 Http Post shows unknown error in normalizedNames for capacitor project

I am calling my Wordpress REST JSON API in my Ionic Capacitor Project.
But i am getting the error shown in image below.
Ionic Capacitor HTTP Error
This is my code
const httpHeader = { // constant for http headers
headers : new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*'
})
};
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}
private dataExtract(res: Response){ // This method extract data from the request response
const body = res;
return body || {};
}
private errorHandler(error: HttpErrorResponse){ // Method for error handler
console.error(error.error instanceof ErrorEvent?`Error message:
${error.error.message}`:`Error status: ${error.error.data.status} Body: ${error.error.message}`);
return throwError(`${error.error.message}`);
}
When i call the createComment function it shows error see in image above. I have tried enable CORS with cordova-plugins-whitelist but still it shows error.
But this api is working fine in postman. I am using this in postman.
URL: https://www.readymadecode.com/wp-json/wp/v2/comments/create
Method: POST
Body: {
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
}
Please help how can i solve this error.
after try all the methods available on google, i able to solve this issue by simply removing the httpHeader from the api.
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}

Firebase Dynamic Link pass custom parameters to iOS and android

I have a custom function in python to build the dynamic link:
def generate_dynamic_link(link, title=None, image=None, description=None, short=True, timeout=10):
api_url = FIREBASE_DYNAMIC_LINK_API_URL
domain = DYNAMIC_LINK_DOMAIN
apn = APP_APN
isi = APP_ISI
ibi = APP_IBI
payload = {
"dynamicLinkInfo": {
"domainUriPrefix": domain,
"link": link,
"androidInfo": {
"androidPackageName": apn,
},
"iosInfo": {
"iosBundleId": ibi,
"iosAppStoreId": isi
},
"socialMetaTagInfo": {
"socialTitle": title,
"socialDescription": description,
"socialImageLink": image
}
},
"suffix": {
"option": "SHORT" if short else "UNGUESSABLE"
}
response = requests.post(api_url, json=payload, timeout=timeout)
data = response.json()
if not response.ok:
raise Exception(data)
return data['shortLink']
I want to pass two parameters to the android and ios app. How can I Do that?
Example:
?type=user&username=testuser
I wrote my first Medium article about this (it’s not a great tutorial) but it shows how to do this. You are correct with how you pass data using ?yourDataHere at the end of your link.
https://augustkimo.medium.com/simple-flutter-sharing-and-deeplinking-open-apps-from-a-url-be56613bdbe6
Then you can handle the deep links by calling the function below. Pretty much you can get the link used to open the app, then get the data from that URL/link string
//ADD THIS FUNCTION TO HANDLE DEEP LINKS
Future<Null> initUniLinks()async{
try{
Uri initialLink = await getInitialUri();
print(initialLink);
var dataFromLink = initialLink.toString().split(‘?’)[1];
print(dataFromLink);
} on PlatformException {
print('platfrom exception unilink');
}
}

Angular HttpClient calls are missing query string and Authorization header

When Angular makes a GET call using HttpClient, the query parameters and Authorization header are missing on the request in our QA environment. When running Angular locally, pointed to the QA APIs, it sends them both as expected.
Here's how the query parameters are set:
const params = new HttpParams().set('schedulingOnly', schedulingOnly ? 'true' : 'false');
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', { params });
Here's how the Authorization header is set (interceptor):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
const request = request.clone({
headers: request.headers
.set('Authorization', 'Bearer ' + sessionStorage.getItem('access_token'))
});
return request;
}
Here's what Chrome dev tools is showing:
That's all the basic information, but below is additional information about things I've tried without success.
Is this a CORS issue? - While searching for others with this issue, I came across a lot of CORS issues. I do not believe that's the case here because Angular and the APIs are on the same domain and I can run Angular locally and hit the APIs no problem.
Do query params get sent if I hardcode them into the url? - Yes. The following worked for the query params: return this.httpClient.get(this.getBaseUrl() + '/domain/getAll?schedulingOnly=true');
Is this something wrong with the interceptor? - I don't believe so. Console.log() statements show all the expected points in code being hit. In fact, the request object after the interceptor adds the auth header shows it on there.
I also tried setting directly without the interceptor, but no luck.
const obj = {
headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') },
params: { 'schedulingOnly': schedulingOnly ? 'true' : 'false' }
};
return this.httpClient.get<any>(this.getBaseUrl() + '/domain/getAll', obj);
There are no js errors in the console except the 401 error
QA web server is IIS
APIs are ASP.NET Core
Angular is embedded within an ASP.NET Web Forms project (due to migrating that legacy code into Angular incrementally)
The issue was that PrototypeJs was interfering with Angular. This led to the issue, but no warnings or errors, so it was just silently causing this issue. PrototypeJs is used in the containing ASP.NET Web Forms app that Angular is embedded into. The reason this was working locally, but not in QA is because I actually did have functionality to not load PrototypeJs if it was an Angular page, due to noticing other issues before, but that wasn't working in QA due to the site starting on a subpath, not directly on the host, so that functionality of not loading PrototypeJs wasn't working.
Have you tried with the shorter version of adding header in your interceptor:
const request = request.clone({
setHeaders: { 'Authorization': 'Bearer ' + sessionStorage.getItem('access_token') }
});
Interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (environment.useHttpMockRequestInterceptor) {
return this.useMockData(request);
} else {
request = this.AddAuthenticationHeader(request);
return next.handle(request);
}
}
private AddAuthenticationHeader(request: HttpRequest<any>) {
return request.clone({
setHeaders: {
Authorization: `Bearer ${sessionStorage.getItem('access_token')}`
}
});
return request;
}

flutter: HTTP get request - disable encoding parameters

I'm trying to make a demo app with flutter and trying to fetch products from a demo magento site.
This is my code:
Future<List<Product>> fetchProducts() async {
final params = <String, String>{
'searchCriteria[filter_groups][0][filters][0][condition_type]': 'in',
'searchCriteria[filter_groups][0][filters][0][field]': 'type_id',
'searchCriteria[pageSize]': '20',
'searchCriteria[filter_groups][0][filters][0][value]': 'simple,configurable,bundle',
'searchCriteria[currentPage]': '1',
'searchCriteria[sortOrders][0][field]': 'created_at',
'searchCriteria[sortOrders][0][direction]': 'DESC'
};
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
final response =
await http.get(uri, headers: {HttpHeaders.authorizationHeader: "Bearer qb7157owxy8a29ewgogroa6puwoafxxx"});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final data = json.decode(response.body);
final products = data["items"] as List;
return products.map<Product>((json) => Product.fromJson(json)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
When I debugged, the response was 400 - Bad request. I guess that because the uri was encoded to include percentage characters as I printed as below:
So how can I disable encoding the uri?
Thank you, guys.
I believe you should replace:
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
with:
var uri = Uri.https('demo.com', '/rest/v1/default/products', params);
more on this: Uri.https
more on: replace
example result:
regardless of this, if I try with your params, the library behaves normal and encodes the special characters. (see more here)
if we put the actual request in the browser to check the response:
https://demo.mage-mobile.com/rest/v1/default/products?searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[filter_groups][0][filters][0][field]=type_id&searchCriteria[pageSize]=20&searchCriteria[filter_groups][0][filters][0][value]=simple%2Cconfigurable%2Cbundle&searchCriteria[currentPage]=1&searchCriteria[sortOrders][0][field]=created_at&searchCriteria[sortOrders][0][direction]=DESC
we get the following response:
And this brings me to my initial suspicion: the API does not support this call.
Maybe you should also check this type of param from your code: 'searchCriteria[filter_groups][0][filters][0][condition_type]', it seems you are trying to acces some information from a collection but you actually writing a string...
try removing the quotes (' bla bla ') from these params id... also try to put the request direcly in the browser(or postman) to see it work.
About the encoding (changing [ to %5B) -- this is normal and it should happen.

XDomainRequest in IE is giving Access is Denied error

This is the code I am using is as follows down below:
I am using IE9 and am unable to see the request being sent in the Network tab. I do have Access-Control headers set in the JSP as:
<% response.setHeader("Access-Control-Allow-Origin", "*");%>
Code to get the AJAX HTML Content from the JSP:
if ($.browser.msie && window.XDomainRequest) {
var xdr = new window.XDomainRequest();
xdr.open("GET", "http://dev01.org:11110/crs/qw/qw.jsp?&_=" + Math.random());
xdr.contentType = "text/plain";
xdr.timeout = 5000;
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function() {
alert(xdr.responseText);
};
xdr.send(null);
} else { ...... }
I am getting a Access is Denied Error. Any help would be much appreciated!
Requests must be targeted to the same scheme as the hosting page
In your example you are doing request to:
http://dev01 ...
And you should do this from HTTP protocol.
For example:
If your site, where js script is located: http://dev.org
You can do this:
xhr = new XDomainRequest();
xhr.open("GET", "http://dev01.org?p=1");
but this throws "Access denied":
xhr = new XDomainRequest();
xhr.open("GET", "https://dev01.org?p=1");
My experience with XDomainRequest is that it doesn't respect Access-Control-Allow-Origin: *. Instead, you must specify the domain. This can be obtained from the HTTP_REFERER header if you need to dynamically generate it, or if you are only expecting requests from one domain you can set it manually. This article might help.
<% response.setHeader("Access-Control-Allow-Origin", "http://dev01.org");%>

Resources