Querying data remotely using New Relic API throwing "404 error" - api

Im using the following AJAX request to send request to New Relic, however its always throws "404 Not Found" error.
Following is the code:
var client = new XMLHttpRequest();
client.open("GET", "https://insights-api.newrelic.com/v1/accounts/REMAINING.URL", true);
client.setRequestHeader("Accept", "application/json");
client.setRequestHeader("X-Query-Key", "QUERY.KEY");
client.send();

Since the origin of the XMLHttpRequest (XHR) or Ajax is different to the requested API's URL, Cross-origin resource sharing (CORS) prevents from accessing the API. Hence, this doesn't work. To implement this, the API will have to be requested by the back-end via .NET, JAVA, PHP, Python, etc. any server side technology and the result will have to be sent to the client Ajax calls.

Related

How can we capture HTTPWebRequest in .net core using Fiddler

I am sending http request to sandbox api which sometimes returns positive response but sometimes it returns bad request with same request data and headers. So I want to debug this request using fiddler during I run the .net core code hitting that api.
But I am not able to find any way to that. Can any one please help me out for the same. I have tried following code to do this:
var requestMessage = GenerateRequestMessage(HttpMethod.Put, uri, query);
requestMessage.Content = new ObjectContent<T>(value, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null);
IWebProxy proxy = new WebProxy("127.0.0.1", 8888);
HttpClient.DefaultProxy = proxy;
return _httpClient.SendAsync(requestMessage);
but fiddler is not capturing this api request.

Pinterest CORS error when retrieving picture

For a project, I retrieve pictures from multiples Social Network. I use Pinterest, and I can list the pins and display them with the URL. But when I want to download a picture with an XMLHttpRequest, I receive a CORS error.
Is it because of the policy of Pinterest or is there an other way to do I?
Here is my code
console.log("Url de l'image: " + this.snURL);
//bug avec Pinterest
var xhr = new XMLHttpRequest();
var _self = this;
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
_self.initRealisationLocalStorage();
workInProgress.Start('Traitement de l\'image');
workInProgress.Info('Traitement de l\'image');
$scope.uploadPhotoNotLocalstorage(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', this.snURL);
//xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.responseType = 'blob';
xhr.send();
});
If someone have a solution or ran explaination I'll be happy to hear it
When calling another domain from a browser directly (javascript) there is a security to prevent arbitrary inclusion of external data.
When this is allowed, it is normally the server who define the CORS header "Access-Control-Allow-Origin" but I guess this is not acceptable for Pinterest to add every domains calling their API.
For that they recommend to use their SDK here and it will use the redirect url you configure in your Pinterest App. as a fallback, otherwise they will use the postMessage API
I don't think you can just make AJAX calls straight to their API from your JavaScript for this reason (CORS restriction on the browser side), see this post.
Another possibility is to create a proxy backend on your side (like a node.js project) which make the query to the Pinterest API and then you query that proxy on your side from your Javascript AJAX
You will not have CORS issue as the backend called would be on your side, and even it is deployed in a different domain you can set the CORS headers on that backend yourself.
I think the SDK way would address you issue and it looks to be the only way to do it when calling the API from a browser directly.

Moqui REST API call fail with error code 403

From my Angular 2 application I am trying to get data from Moqui but the request always fails with the error code 403.
Here is the REST API call implementation
getExample() {
let url = 'http://localhost:8080/rest/s1/example/examples'
let headers = new Headers({ 'Authorization': 'Basic
am9obi5kb2U6bW9xdWk='});
headers.append('Accept', 'application/json, text/plain, */*');
headers.append('Content-Type', 'application/json; charset=UTF-8');
let options = new RequestOptions({ headers: headers });
let response = this.http.get(url, options).map(res => res.json());
return response;
}
The Moqui logs :-
REST Access Forbidden (no authz): User null is not authorized for View on REST Path /example/examples
There is also a similar question Moqui Rest Nginx but from the answer I do not know that where I have to change the settings in Moqui.
On the client console the error is :-
XMLHttpRequest cannot load http://localhost:8080/rest/s1/example/examples. Response for preflight has invalid HTTP status code 403
But with a rest client like YARC it works :-
You must authenticate for REST API calls except for Service REST API paths that are configured to not require authentication (like the /mantle/my end points in the mantle.rest.xml file in the mantle-usl component).
You have authentication but then there is one other step: authorization. In general if authc is required then authorization is also required. This is done with database records usually either in seed data and can also be added using the System app that is included in the default Moqui runtime (ie the moqui/moqui-runtime repository).
There is an example of authorization setup for Service REST API calls in the MantleSetupData.xml file. The main difference from screen authorization is that the artifact type to use is 'AT_REST_PATH'. Here is that file on GitHub (right near the top of the file):
https://github.com/moqui/mantle-usl/blob/master/data/MantleSetupData.xml
The best documentation for most things to do with REST requests in Moqui, is currently in the comments in the 'rest.xml' file that actually processes the incoming requests (ie handles the /rest path). You can see this on GitHub here:
https://github.com/moqui/moqui-runtime/blob/master/base-component/webroot/screen/webroot/rest.xml

Signing into Backand Using BackAnd SDK

Attempting to sign in (and enter a session) using user credentials in an Angular app using the Backand SDK. From the Backand docs I am attempting to sign in using the Backand.signin() method (from my local) which looks to be initially sending an OPTIONS http request to the API which unfortunately is causing this cross origin error:
XMLHttpRequest cannot load https://api.backand.com/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:xxxx' is therefore not allowed access. The response had HTTP status code 400.
The exact response from the endpoint is: {"error":"unsupported_grant_type"}
I've combed through the documentation extensively but can't find anyone else having these errors.
This is exact code I am using:
function Login(username, password, callback) {
Backand.signin(username, password).then(function(response){
console.log(response);
}, function(error){
console.log(error);
});
}
The error is logged to the console as a null object.
It looks like the error was in fact on my end.
While attempting to set up my own Authorization service in my Angular app I inadvertently was adding an encoded Authorization token header somehow. When the requests were being made to Backand from the Backand SDK, the headers were not correctly set and thus causing issues.

IIS 7 Serves GET request correctly to browser but throws timeout exception for API request

I am running a very simple Web application (Asp.Net MVC3) on Win 7 IIS.
I have a very simple HTTP GET API which returns hello world.
Calling:
http://localhost/helloworld
Returns:
Hello World!
This works perfectly over a browser.
But when I write an app which tries to pull this URL using a webclient, I get the following error:
{"Unable to read data from the transport connection: The connection was closed."}
My Code is as follows
WebClient web = new WebClient();
var response = web.DownloadString("http://localhost/helloworld");
My IIS Settings are as follows
What should I be looking at? I have been at this for hours and I have run out of options to try! Any help will be really appreciated!
Thanks.
I suspect it's because WebClient does not send some of the HTTP headers:
A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing. http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx
Try using HttpWebRequest instead. http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
I finally figured out what the issue was and instead of it being an IIS specific issue - which I was leaning towards, it turned out to be an issue with the code that I wrote.
Adding details here incase someone else runs into a similar problem.
I had the following method in my code which I was using to send the response of the request as a JSON object.
private void sendJsonResult(string result) {
Response.StatusCode = 200;
Response.Headers.Add("Content-Type", "application/json; charset=utf-8");
Response.Flush();
Response.Write(result);
Response.End();
Response.Close(); // <-- This is the problem statement
}
On digging around a bit, I found out that we should not be doing a Response.Close().
A better explanation of this is here.
Once I removed that line, it started working perfectly - both in my consuming app as well as the web browser, etc.
If you will read the link above, you will clearly understand why we should not be using a Response.Close() - so I will not go into that description. Learnt a new thing today.