For a while, I was trying to to get my local angular build to serve with HTTPS (to learn, and to be sure I wasn't going to run into any SSL issues with the final app). However, after no success, I went back to using ng serve, however, all my AJAX requests are failing now. I run a local VM serving a Slim API, and have CORS setup. However, I started seeing the following error:
The 'Access-Control-Allow-Origin' header has a value 'http://gamersplane.local' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.
Looking at the call in the network tab, I see that the origin header is indeed null, and looking through my code, I don't mess with the origin header (not sure if you can?). I do set an Authorization header, but that's it? Here's my API service:
private addToken(headers: HttpHeaders) {
let token = localStorage.getItem('token');
if (token) {
headers = headers.set('Authorization', 'Bearer ' + token);
}
return headers;
}
private constructParams(data?: Object) {
// Object.keys(data).reduce((params, key) => params.set(key, data[key]), new HttpParams());
let params = new HttpParams();
for (let key in data) {
if (typeof data[key] !== 'object') {
params = params.set(key, data[key]);
} else {
for (let oKey in data[key]) {
params = params.set(key + '[' + oKey + ']', data[key][oKey]);
}
}
}
return params;
}
get<T = any>(path: string, data?: Object): Observable<T> {
let headers = new HttpHeaders();
headers = this.addToken(headers);
return this.http
.get<T>(environment.apiDomain + path, {
headers: headers,
params: this.constructParams(data)
});
}
Any advice?
This isn't a Angular issue (I think): you have to allow all origins to access your backend. Just set the origin header to *.
You can also create a proxy for your calls :
proxy.conf.json
{
"/api": {
"target": "http://1.2.3.4:5/",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
Fiddle around with the settings, you'ff figure it out.
When you serve,
$ ng serve --proxy-conf ./proxy.conf.json
With a proxy, your server (ng serve) will make the request, instead of the backend, thus eliminating the need to comply with cross origin constraints.
now, your urls in your services won't be
let url = 'http://1.2.3.4:5/api/'
But just
let url = '/api/'
And the proxy will handle this for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With