I have encountered a strange issue with a GET request that I am stuck on.
I am calling a GET request from my ASP.Net application that works fine in postman but does not hit my userGETReq.onload.
function getUser(username){
userGETReq.open("GET", userURL + "/" + username);
userGETReq.send();
userGETReq.onload = () => {if(userGETReq.status === 200){//cool stuff }}
I am running on a localhost in the browser - the function to start this is being called from a form that returns false.
<form onsubmit="login(this); return false">
POSTMAN
Picture of successful postman response for the GET request
I have other GET requests from the same application that work.
The only difference between this and the other one that works is that it has a 'variable' that gets passed in and has a set route:
[Route("api/User/{username}")]
public List<User> Get(string username)
This is how my CORS is set up
that is the problem
CORS:
EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
Any help would be greatly appreciated!
The waring I am getting:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:56390/api/user/test3. (Reason: CORS request did not succeed).
to resolve CORS issue, you can write another method in service as follows
Every time service call is made, OPTIONS is triggered first to check if the service call is allowed and once the OPTIONS returns allowed, actual method is invoked
//here you can add URL of calling host or the client URL under HEADER_AC_ALLOW_ORIGIN
#OPTIONS
#Path("/yourservice/")
#LocalPreflight
public Response options() {
String origin = headers.getRequestHeader("Origin").get(0);
LOG.info(" In options!!!!!!!!: {}", origin);
if ("http://localhost:4200".equals(origin)) {
return Response.ok()
.header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "GET,POST,DELETE,PUT,OPTIONS")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN, "http://localhost:4200")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS, "content-type")
.build();
} else {
return Response.ok().build();
}
}
Related
I have a Sitecore site and I'm trying to make API calls from a controller. For some reason API always returns the 404 not found, but it also executes the code correctly and returns the content. I tried to call the same API endpoint via Postman and returned the 200 code with content.
Here's my RouteConfig:
routes.MapRoute("Feature.DataIntegration.Api", "api/dataintegration/{action}",
new
{
controller = "DataIntegration"
});
Here's my API (I tried to use [HttpGet] attribute, but it didn't work):
public string test1()
{
return "Asdas";
}
This is my RestSharp code:
var url = "http://tdev.xxx.cd.local/api/dataintegration/test1";
var client = new RestClient(url);
var request = new RestRequest();
IRestResponse response = client.Execute(request);
This is Postman's return:
This is when the result from RestSharp (I also tried with httpclient, the same result):
I have tried to disable my firewall, but doesn't work neither.
How can I fix the 404 not found? If I don't fix this, does this affect the API once deployed to a real server?
Bear with me for any mistakes/wrong terminology since I am new to all this. I am using meteor to develop my project and i need to make a get request to an external API. (I already added meteor add http) Below is my code:
HTTP.call( 'GET', 'url', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
If i use the code inside my Client folder in Meteor I get the following error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access meteor It has something to do with CORS which I didn't understand how to implement. If I use the code above in my Server side I do get the correct response in the console but how do I use it as a var on my client javascript code?
Tou can use .call function of HTTP and pass your header in options:
HTTP.call(method, url, [options], [asyncCallback])
Arguments
method String
The HTTP method to use, such as "GET", "POST", or "HEAD".
url String
The URL to retrieve.
asyncCallback Function
Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.
Options
content String
String to use as the HTTP request body.
data Object
JSON-able object to stringify and use as the HTTP request body. Overwrites content.
query String
Query string to go in the URL. Overwrites any query string in url.
params Object
Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL.
auth String
HTTP basic authentication string of the form "username:password"
headers Object
Dictionary of strings, headers to add to the HTTP request.
timeout Number
Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.
followRedirects Boolean
If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true.
npmRequestOptions Object
On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation.
beforeSend Function
On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send.
Souce: Here
Fixed it. On client side
Meteor.call("getURL",'url',{},function(err,res){
if(err){
console.log('Error: '+err);
}
if(!err){
console.log('Response: '+res);
}
and on server
Meteor.methods({
'getURL': function(url_l){
console.log("Request: "+url_l)
return HTTP.get(url_l)
}
});
Executing Angular2 http call to the offline server doesn't provide much info in it's "error response" object I'm getting in the Observable's .catch(error) operator or subscription error delegate (they are both share the same info actually). But as you can see on the screen shot of the console there's actual error was displayed by zone.js somehow.
So, how can I get this specific error info (net::ERR_CONNECTION_REFUSED)?
Thanks.
Whenever server do not respond, response.status will be always equal to 0 (zero)
{
type: 3, //ResponseType.Error
status: 0, // problem connecting endpoint
}
Also note, when you are performing CORS request, but origin (url in browser) is not authorized (not in allowed list of host names configured in remote endpoint) the response would be similar to above, with exception to type attribute which will be equal to 4 = ResponseType.Opaque...
This means, connection was made, but for instance, OPTIONS request returned with headers which do not contain origin or HTTPS request was performed from HTTP origin.
You can handle the error messages so they are easier to read. This can definitely be expanded on too:
public Get() {
return this.http.get(this.URL).map(this.extractData)
.catch(this.handleError);
}
public extractData(res: Response) {
let body = res.json();
return body || {};
}
public handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
Check out this part of the docs on error handling.
Without digging in the code, my expectation is that if the server is unreachable, then no response can be returned from the server. Therefore the Response object remains its initialized state.
I cannot interecept error from http post
a part of my mservice (http post method)
addApplicationLink(applicationLink: ApplicationLink){
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json; charset=utf-8']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});
in my component :
addApplicationLink() {
//todo
this.addNewLink = false;
/* check if must be done after call real rest service */
//this.applicationLinks.push(this.applicationLinkAdd);
this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)
.subscribe(data => {
this.applicationLinks.push(this.applicationLinkAdd)
},
error => {
// handle error
console.error('this an erreor ' + error.status)
}
)
When user tries to add two same applicationlinks , the backend returns an error 409
But when I execute , error.status displays 200 in browser console
I see also in browser console
XMLHttpRequest cannot load http://localhost:7001...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 409.
rem : Http post is made with json , thus there is a prefligth call
Have you an idea to intercept error 409 ?
In fact, your server doesn't send back the CORS header (Access-Control-Allow-Origin' header is missing). This prevent the browser from providing the actual 409 error to the Angular2 application within the browser.
You need to fix first the problem on the server and you will be able to see this 409 error.
For more details about how CORS works, you could have a look at this article:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
When I try to call an external server for JSON queries in Meteor with the Meteor.http.call("GET") method I get the error message "not allowed by Access-Control-Allow-Origin".
How do I allow my meteor app to make HTTP calls to other servers?
Right now I run it on localhost.
The code I run is this:
Meteor.http.call("GET",
"http://api.vasttrafik.se/bin/rest.exe/v1/location.name?authKey=XXXX&format=json&jsonpCallback=processJSON&input=kungsportsplatsen",
function(error, result) {
console.log("test");
}
);
There are other questions similar to this on StackOverflow.
You're restricted by the server you're trying to connect to when you do this from the client side (AJAX).
One way to solve it is if you have access to the external server, you can modify the header file to allow some, or all origins by:
Access-Control-Allow-Origin: *
However, if you place the call on the server side and not provide a callback function, the call will be made synchronously, thus not with AJAX, and it should succeed.
Here's
Meteor.methods({checkTwitter: function (userId) {
this.unblock();
var result = Meteor.http.call("GET", "http://api.twitter.com/xyz", {params: {user: userId}});
if (result.statusCode === 200) return true
return false;
}});