I'm new to angular2 and to be fair I have very few knowledges which I try to fix, however I've run into some issues about cross site request, trying to access a service from another application but I have this issue whatever I try to do
XMLHttpRequest cannot load https://hr/Team/EditEmployeeInfo.aspx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54396' is therefore not allowed access. The response had HTTP status code 401.
This is my angular2 service and I've tried something like this
getUserHrtbProfile(userId): Promise<any> {
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET, PUT, POST, DELET');
headers.append('Access-Control-Allow-Origin', '*');
var apiUri: string = "https://hrtb/Team/EditEmployeeInfo.aspx?emplid={0}&Menu=InfoEmployee&T=0".replace("{0}", userId);
return this.http.get(apiUri, headers).map(result => result.json()).toPromise();
}
and this is my component
this.bannerService.getUserHrtbProfile(this.userId).then(hrtbJson => {
this.hasHrtbAccess = hrtbJson.HasHrtbAccess;
this.hrtbProfileUrl = hrtbJson.HrtbProfileUrl;
}).catch(err => {
this.hasHrtbAccess = false;
});
I've search a solution on my problem but still could not find one that suits my need.
Angular 2 http request with Access-Control-Allow-Origin set to *
But most important, is this an angular2 problem that I need to solve? Or in fact as I've read it should have been handled by the team that exposes the API?
Thank you all.
You need to enable CORS on your API backend.
Only for testing purpose you could use this Chrome Extension to simulate CORS on your api backend:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
You are trying to make request on other domain, this is what you can not resolve here. try with making request at you backed code, this will resolve you issue.
Related
Stuck on this problem where I received this error everytime making POST request to my actix-web server.
CORS header 'Access-Control-Allow-Origin' missing
my javascript (VueJs running on localhost:3000) :
let data = //some json data
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/abc");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = () => {
console.log(xhr.responseText);
}
xhr.send(JSON.stringify(data));
My Actix_Web server (running on localhost:8080) :
#[actix_web::main]
async fn main() {
HttpServer::new(move || {
let cors = Cors::default()
.allowed_origin("http://localhost:3000/")
.allowed_methods(vec!["GET", "POST"])
.allowed_header(actix_web::http::header::ACCEPT)
.allowed_header(actix_web::http::header::CONTENT_TYPE)
.max_age(3600);
App::new()
.wrap(cors)
.service(myfunc)
})
.bind(("0.0.0.0", 8080))
.unwrap()
.run()
.await
.unwrap();
}
my cargo.toml dependencies
[dependencies]
actix-web = "4"
actix-cors = "0.6.1"
...
Got any idea?
Okay, so I've done some testing. If you're writing a public API, you probably want to allow all origins. For that you may use the following code:
HttpServer::new(|| {
let cors = Cors::default().allow_any_origin().send_wildcard();
App::new().wrap(cors).service(greet)
})
If you're not writing a public API... well, I'm not sure what they want you to do. I've not figured out how to tell the library to send that header. I guess I will look at the code.
UPDATE:
So funny story, this is how you allow specific origins:
let cors = Cors::default()
.allowed_origin("localhost:3000")
.allowed_origin("localhost:2020");
BUT, and oh boy, is that but juicy. The Access-Control-Allow-Origin response header is only set when there is a Origin request header. That header is normally added by the browser in certain cases 1. So I did that (using the Developer tools in the browser). What did I get? "Origin is not allowed to make this request". I set my origin header to localhost:3000. Turns out, the arctix library simply discards that header if no protocol was provided... (e.g. http://) (I assume it discards it, if it deems its format invalid). That internally results in the header being the string "null". Which is, checks notes, not in the list of allowed origins.
And now the grand finale:
Your origin header needs to be set to (by either you or the browser): "http://localhost:3000".
Your configuration needs to include: .allowed_origin("http://localhost:3000").
After doing that, the server will happily echo back your origin header in the Access-Control-Allow-Origin header. And it will only send that one.
I've no idea if any of that is what the standard specifies (or not). I encourage you to read through it, and if it doesn't comply, please open an issue on GitHub. I would do it myself, but I'm done with programming for today.
Cheers!
I'm working on my project which includes Angular 9 application using firebase functions. I deployed some function, which should update some values on the Firebase Realtime Database. Unfortunately, I encountered a problem with CORS policy if I use my API.
After adding middleware to my express server, where I added these code, the problem still occurs.
app.post('/changeQuantity', permit(), (request: any, response: any) => {
response.status(200).send({ data: { Message: 'Changing order quantity - success.' } });
})
export default function permit() {
return (req: any, _res: any, next: any) => {
_res.setHeader('Access-Control-Allow-Origin', '*');
_res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
next();
};
}
I noticed, that I get this error when frequently requesting API.
Here is the error which server returns:
Access to fetch at [here is a link to my API endpoint] from origin [my origin] has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
Did anybody have the same issues with the firebase functions API? Could it be related to frequent requests of my API endpoints from the development environment? Thanks in advance.
Try using response.header to set the CORS properties, like this
app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
next();
});
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();
}
}
My post works in postman but doesn't work inside my app. What am I doing wrong?
let data = obj;
let url = 'https://us123.api.mailchimp.com/3.0/lists/{somenumber}/members';
let username: string = 'user';
let password: string = 'mytokenhere';
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this._http.post(url, data, {headers: headers}).subscribe(
data => this.response(data),
error => this.response(error)
);
I'm getting a CORS error in app:
'XMLHttpRequest cannot load https://us123.api.mailchimp.com/3.0/lists/{{somenumber}}/members. 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:4200' is therefore not allowed access. The response had HTTP status code 501.'
Mailchimp doesn't support client side calls to their API. What you would need to do is setup a server that can proxy the requests from the browser to Mailchimp. There isn't much you can do client side to get it to work if the Mailchimp API doesn't provide the CORS response headers.
If your API that you create is on the same domain as the website, then the CORS issue would be eliminated (or you can also fix by setting the appropriate headers)
See the note under Authentication:
https://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/
More Info:
https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/
Trying to get signalr up and running.
I keep getting 2 errors back from the server:
GET negotitate url returns 500 Internal Server Error
XMLHttpRequest cannot load http://localhost:10772//signalr/negotiate ...
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 500.
Screenshot provided.
Any ideas?
]1
OK, found it out myself. Spelling error.
The name of the hub mentioned was incorrect.
changed:
var proxy = this.connection.createHubProxy('chattAppHub');
to:
var proxy = this.connection.createHubProxy('ChatAppHub');
In the backend:
[HubName("ChatAppHub")]
public class ChatAppHub : Hub ...
inside startup.cs
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
appBuilder.MapSignalR(hubConfiguration);
appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
This fixed it for me:
C# Startup.cs tweak:
app.MapSignalR(new HubConfiguration{EnableJSONP = true});
JavaScript tweak:
connection.start({ jsonp: true })
We need JSONP anyways so for us it was a good solution.
I had the same problem, it is all about CORS.
You should add Host URL in CORS config in Sturtup.cs, Have look at:
https://stackoverflow.com/a/59891997/854405