Failed to connect with REST web service - javascript

I have one web service in jersey that deploy on appache server, and I'm trying to connect that server but I get the following error :
Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
my service.ts file code is below
getlogin(): Observable<ILogin[]> {
return this._http
.get(this._loginurl, this.headers)
.map((response: Response) => <ILogin[]> response.json())
.catch(this.handleError);
}
this is my server url
_loginurl='http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/'+this.encodedString;
please help me to solve this..thank you!!

Try This
getlogin(): Promise<ILogin[]> {
return this.http.get(this._loginurl)
.toPromise().then(response => <ILogin[]>response.json().data)
.catch(this.handleError);
}

The error clearly says:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is not an error with angular2 itself. But it's more to do with your CORS configuration on server side.
You have to set Access-Control-Allow-Origin header in your response from your service. You can set something like below which says you basically allow any resource:
Access-Control-Allow-Origin: *

try this:
import {Headers} from "#angular/http";
let headers=new Headers({
});
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin','*');
getlogin(): Promise<ILogin[]> {
return this.http.get(this._loginurl,{headers:headers}))
.toPromise().then(response => <ILogin[]>response.json().data)
.catch(this.handleError);
}

Related

'Blocked by CORS policy', but Header is present

I created a REST API using Go and fasthttp and a frontend using Vue. Everytime I make an API request, I get the error Access to XMLHttpRequest at 'http://localhost:55555/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource in my Browser console. The only time I don't get this error, is the /auth/check route. Also I made an OPTIONS-Request to my backend and got all the CORS Headers. I don't get them if I make a POST or GET request, but I don't know why.
Backend:
webRouter := router.New()
auth := webRouter.Group("/auth")
auth.GET("/check", authCheck)
auth.POST("/login", authLogin)
auth.GET("/logout", authCheck)
err = fasthttp.ListenAndServe(":"+port, func (ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Set("Access-Control-Allow-Headers", "authorization, content-type, set-cookie, cookie, server")
ctx.Response.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
ctx.Response.Header.Set("Access-Control-Allow-Credentials", "false")
webRouter.Handler(ctx)
})
if err != nil {
panic(err)
}
Frontend request:
axios.create({
baseURL: 'http://localhost:55555'
}).post('/auth/login', {
email: this.email,
password: this.password
}).then(response => {
console.log(response)
}).catch(err => {
console.log(err)
})
I fixed my issue. I read the docs of fasthttp another time and figured out that the ctx.Error() method clears all headers. Instead I am now setting the response code and error message manually and everything works fine.

Access-Control-Allow-Origin issue in ktor cors header

I am building a simple REST API using ktor and used cors but when i send a simple get request with no headers data the server works fine but if i want the client to have say key:1 the server doesn`t respond me correctly, it says the problem is
Failed to load http://127.0.0.1:8080/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
so here is my ktor code
install(ContentNegotiation) {
gson {
}
}
install(ForwardedHeaderSupport)
install(DefaultHeaders)
install(CORS)
{
method(HttpMethod.Options)
method(HttpMethod.Get)
method(HttpMethod.Post)
method(HttpMethod.Put)
method(HttpMethod.Delete)
method(HttpMethod.Patch)
header(HttpHeaders.AccessControlAllowHeaders)
header(HttpHeaders.ContentType)
header(HttpHeaders.AccessControlAllowOrigin)
allowCredentials = true
anyHost()
maxAge = Duration.ofDays(1)
}
...
get("test"){
val a = call.request.headers["key"]
println(a)
call.respond(Product(name = a))
}
and my javascript code looks like this....
fetch('http://shop-ix.uz:8080/test', {
headers: {
"key": "1"
})
.then(response => response.json())
.then(json => {
console.log(json);
})
please help me
You need to whitelist your headers like this:
install(CORS) {
header("key")
}
This needs to be done with every custom HTTP header you intend to use.
Make sure all the headers and required methods should be allowed during Ktor CORS installation. I was facing the same issue, then I realized that I didn't add allowHeader(HttpHeaders.AccessControlAllowOrigin)
Although in the request header it was present. Because of that I am getting forbidden error (403)!
My Request Header!
Axios({
method: 'GET',
url: 'http://127.0.0.1:8080/connect',
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
params: {
...
}
})
Allowing CORS
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Post)
allowMethod(HttpMethod.Get)
allowHeader(HttpHeaders.AccessControlAllowOrigin)
allowHeader(HttpHeaders.ContentType)
anyHost()
}
Check that what your request header wants is allowed on the server during CORS.
install(CORS) {
exposeHeader("key")
}
difference between header and exposeHeader - first allow to make call with this header, but second allow to use it on client side

Can't get request a link with Axios due to No 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to use the cryptocompare api to get a list of coindata with axios but I can't figure out how to get around this issue I believe it's a CORS issue, but I am not sure.
The full error is as follows:
Failed to load https://www.cryptocompare.com/api/data/coinlist/: 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 524.
I am using axios with the following code:
addCoinData(coinData) {
axios.get('https://www.cryptocompare.com/api/data/coinlist/')
.then(res => {
const crypto = res.data;
this.setState({crypto: crypto});
})
.catch(function (error) {
console.log(error);
});
console.log(this.state.crypto);
};
Their API just changed the url for the data that you want to get.
https://min-api.cryptocompare.com/data/all/coinlist
I've successfully made a GET request test with this url with axios as well.
axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
console.log(res.data)
})
.catch(function (error) {
console.log(error);
});
I hope it helps.

Angular 4 Front End hosted on Azure CORS Issue

I'm building a web app with Angular 4 that's trying to POST to the VSTS Rest API. I obviously don't own the service and I'm trying to run in live in Azure and NOT locally (I understand that I can disable CORS in chrome for local testing).
Failed to load
https://app.vssps.visualstudio.com/oauth2/tokenRemovedtoStackOverflow
Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin
'https://blah.azurewebsites.net' is therefore not allowed access. The
response had HTTP status code 400.
Call is basically:
private _appID = blah;
private _tokenRequest = 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={0}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={1}&redirect_uri={2}';
private _returnURI = 'https://blah.azurewebsites.net/';
private headers = new Headers(
{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-type',
'Content-Type': 'application/x-www-form-urlencoded',
});
constructor(private http: Http) { }
getAccessToken(code: string): Observable<IToken> {
const _url = 'https://app.vssps.visualstudio.com/oauth2/' + code;
const body = 'client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion=' +
this._appID +
'&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=' +
code + '&redirect_uri=' +
this._returnURI;
const options = new RequestOptions();
options.headers = this.headers;
return this.http
.post(_url, body, options)
.map((response: Response) => <IToken[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
Currently I have no server/api(AKA the only thing in my source is angular) and it's just running on whatever server Azure web app provides.
Is my only choice to get around the CORS adding a nodejs server to host this in azure?
Access-Control-Allow-Origin and Access-Control-Allow-Headers are response headers. They have no place on your request.
Adding custom headers is one of the triggers of the preflight OPTIONS request that is generating the 400 error.
Removing them should cause the request to be a simple request and might be allowed by the service.
Failing that: Yes, you need to change the host so that it grants you permission.

unable to set 'Access-Control-Allow-Origin' header

I need to access my web api hosted remotely from my react app. On the server side i did below to allow cross domain communication:
import javax.ws.rs.core.Response;
import com.mypackage.ResponseDto;
#Override
public Response fetch(String id, String env) throws ServiceException
{
ResponseDto res = new ResponseDto();
res = updateResp(id, env); // not important
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
When i check from postman i can see cors header correctly set as below:
access-control-allow-origin →*
content-type →application/json
date →Wed, 16 Aug 2017 11:07:16 GMT
server →web
transfer-encoding →chunked
But when i access the same endpoint from react app, browsers starts complaining with below error:
Fetch API cannot load
http://myservices.com/myservice-app/services/. 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:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled
Any idea whats going on here?
Edit#1
Did below change still see the same error:
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.entity(response).build();
I have no experience with whatever Java library you're using, but something like this must work:
#Override
public Response options() throws ServiceException
{
ResponseDto res = new ResponseDto();
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
If the library works like I think it does, this will send a 200 OK on every OPTIONS request you send to your server, with header Access-Control-Allow-Origin = *. That's what you should be aiming for.

Categories

Resources