unable to get the cross domain json response using script tag proxy - sencha-touch

I am using a script tag proxy like this:
Ext.regModel('login',{fields:['status']});
var loginstore = new Ext.data.Store({ model:'login', proxy:{type:'scripttag',url:'myurl',reader:{type:'json',root:'data'}},autoLoad : true,});
loginstore.load();
In that, the url will return the response format below:
{"data":{"status":"error"}}
I am getting the error:
unexpected token :
Why am I getting this error? What are all the other ways to get the json response from cross domain without callback key and yql.

You cannot use scripttagproxy like that. Please have a look at this thread.
After you configure your server and callback function. You might want to try simpler method to call your cross-domain request as follows.
Ext.util.JSONP.request({
url: some_cross_domain_url,
params: {param1: "something", param2: ...}
callback:function(response){
//response here will be JSON object.
}
});
Please also have a look at this simple tutorial about how to configure your JSONP request.

Related

CORS blocking requests in Kotlin lambda but not in identically setup Node lambda

I have a lambda, written in Kotlin with Serverless and CORS just is not working. I feel like I've tried everything. I deployed a Node Lambda with identical sls.sh command and yaml files. The function looks like this
hello:
handler: handler.hello
events:
- http:
path: hello
method: post
cors: true
My responses look like this in both Node and Kotlin:
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": "{\"id\": \"f9f76590-xxxx-xxxx-xxxx-9c8e99238f40\"}"
}
In the Node case this all works great. I make a fetch call like this and it works (omitted the Promise resolutions for brevity):
var makeRequest = function (data) {
fetch('https://{lambda URL}/hello', {
'headers': {
'content-type': 'application/json'
},
'body': JSON.stringify({ data }),
'method': 'POST'
})
}
In the Kotlin case I get this CORS error back
Access to fetch at 'https://{lambda URL}/hello' from origin
'http://127.0.0.1:8080' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I try to "enable CORS" in the API Gateway panel but I get that it's already enabled:
And hit submit I get the error (invalid response status code)
When I hover over the error icon it says "Invalid Response status code specified".
Under Gateway Responses, under every sub item (Default 4XX, Default 5XXX, etc) there are response headers set. This is the same across my Node and Kotlin lambdas.
I'm completely out of ideas at this point.
The only potentially odd thing is I am noticing that in my Node request I see access-control-allow-origin: * in response headers in the browser network panel but in the Kotlin one I don't see it.
From this:
I can see that you haven't created Integration Response in your post method.
Try these configurations:
I discovered my CORS issue was because of server errors. If your server has an error and the API Gateway can't get a response then you get a CORS error because the Gateway itself doesn't have the CORS headers.
While the fix is easy (just handle that server error) it was hard to uncover. I wish this was documented better somewhere so hopefully this is found for others :)
For my case specifically, and why it didn't show up in Node but showed up in Kotlin, was because of types. the browser was sending a type Node automatically corrected the type (number to string) but Kotlin was expecting the type and threw a type error.

How to obtain response to be used on hooks

I am trying to make a simplified version of test report where I am generating a single HTML file report containing only assertion and error response message when there is any (attempting to not publish all the logs and steps).
I understand that we have hooks in karate. However I have looked for karate objects in the github but unable to found any objects where I can extract the response from (to be passed to the js function called on hook)
What I am doing right now is this:
Config:
//karate-config.js
karate.configure('afterScenario', karate.call('classpath:hooks.js'));
Hook:
//hooks.js
//Looking on how to extract the response and log it here
function(){
var info = karate.tags;
karate.log('Tags', info);
}
Am I missing anything on the karate objects? Or this should be achieved in another way?
Thanks a lot!
Try this:
var response = karate.get('response');
EDIT better example:
Background:
* configure afterScenario = function(){ karate.log('***', karate.get("response.headers['X-Karate']")) }
Scenario:
Given url 'http://httpbin.org'
And path 'headers'
And header X-Karate = 'test'
When method get
# this will fail
Then status 400
I have tried with both karate.get('response') and response directly, and both work. If you use karate.call() pass the response as a parameter.

How to call Phishtank API to get JSON response?

It was really painful to find how to call Phishtank API here.
After a lot of searching I was able to find how to call the API. Below is a sample call,
https://checkurl.phishtank.com/checkurl/index.php?url=http://auto.smtpsystems.net/&format=json
But the problem with the above call is that it gives the response in XML format whereas I want the response in JSON format.
Any kind of help will be greatly appreciated.
The problem is that you are making an HTTP GET request. And this method accepts an HTTP POST request
//Custom your request
var requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: "https://checkurl.phishtank.com/checkurl/",
method: 'POST',
json: true,
body: {
url: The URL to check(urlencoded or base64 encoded),
format: 'json',
app_key: Your application key
},
};
//Do the request
request.post(requestOptions, function callback(err, httpResponse, json) {
//Here you json
})
Make sure to use https instead of http in the endpoint url, although in Documentation http is given(as of writing this).
Use HTTP POST request not HTTP GET.
And format is in quotes(double preferred)
# Python implementation
endpoint = "https://checkurl.phishtank.com/checkurl/"
url = "http://www.travelswitchfly.com/"
response = requests.post(endpoint, data={"url": url, "format": "json"})
You have to specify the url, format, and the app_key in the body of the POST request.
I was trying to implement their API in my android application with the help of Retrofit. Their documentation is outdated. After spending 3 hours I come to know a few things.
use this URL https://checkurl.phishtank.com/checkurl/ (do not use URL with http://)
use the below interface for retrofit GET request. it does not work with #Query and it requires #FormUrlEncoded
#FormUrlEncoded
#GET("https://checkurl.phishtank.com/checkurl/")
fun findPhishing(
#Field("format") format: String,
#Field("url") url: String
): Single<Response>

How to properly read POST params with express?

My node app is supposed to POST to an external server, so I'm playing with request from NPM. I want to verify it's working, but I'm not entirely sure I'm doing that right.
I've tried both of these methods
request({
url: url,
method: 'POST',
form: { a: 1}
}
request({
url: url,
method: 'POST',
json: true,
body: { a: 1}
}
In my test when I hit my own server, req.body shows the right object when I do json true. However that just means I'm passing a JSON header. The API I actually need to hit is expecting a normal POST, not JSON.
So when I try to verify that request is working right when I use form, my server says req.body is an empty object.
EDIT
I am posting to external API fine using form, but on my own server, express is leaving request.body as empty object.
See if this works for you:
request.post('http://service.com/upload').form({key:'value'})

Using Node JS to proxy http and modify response

I'm trying to write a front end to an API service with Node JS.
I'd like to be able to have a user point their browser at my node server and make a request. The node script would modify the input to the request, call the api service, then modify the output and pass back to the user.
I like the solution here (with Express JS and node-http-proxy) as it passes the cookies and headers directly from the user through my site to the api server.
proxy request in node.js / express
I see how to modify the input to the request, but i can't figure out how to modify the response. Any suggestions?
transformer-proxy could be useful here. I'm the author of this plugin and I'm answering here because I found this page when looking for the same question and wasn't satisfied with harmon as I don't want to manipulate HTML.
Maybe someone else is looking for this and finds it useful.
Harmon is designed to plug into node-http-proxy https://github.com/No9/harmon
It uses trumpet and so is stream based to work around any buffering problems.
It uses an element and attribute selector to enable manipulation of a response.
This can be used to modify output response.
See here: https://github.com/nodejitsu/node-http-proxy/issues/382#issuecomment-14895039
http-proxy-interceptor is a middleware I wrote for this very purpose. It allows you to modify the http response using one or more transform streams. There are tons of stream-based packages available (like trumpet, which harmon uses), and by using streams you can avoid buffering the entire response.
var httpProxy = require('http-proxy');
var modifyResponse = require('http-proxy-response-rewrite');
var proxy = httpProxy.createServer({
target:'target server IP here',
});
proxy.listen(8001);
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
proxy.on('proxyRes', function (proxyRes, req, res) {
modifyResponse(res, proxyRes.headers['content-encoding'], function (body) {
if (body && (body.indexOf("<process-order-response>")!= -1)) {
var beforeTag = "</receipt-text>"; //tag after which u can add data to
// response
var beforeTagBody = body.substring(0,(body.indexOf(beforeTag) + beforeTag.length));
var requiredXml = " <ga-loyalty-rewards>\n"+
"<previousBalance>0</previousBalance>\n"+
"<availableBalance>0</availableBalance>\n"+
"<accuruedAmount>0</accuruedAmount>\n"+
"<redeemedAmount>0</redeemedAmount>\n"+
"</ga-loyalty-rewards>";
var afterTagBody = body.substring(body.indexOf(beforeTag)+ beforeTag.length)+
var res = [];
res.push(beforeTagBody, requiredXml, afterTagBody);
console.log(res.join(""));
return res.join("");
}
return body;
});
});