How to add CORS request in header in Angular 5
Solution 1:
In my experience the plugins worked with HTTP but not with the latest httpClient. Also, configuring the CORS response headers on the server wasn't really an option. So, I created a proxy.conf.json
file to act as a proxy server. This is for development purposes only.
Read more about this here.
proxy.conf.json
file:
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
I placed the proxy.conf.json
file right next the the package.json
file in the same directory.
Then I modified the start command in the package.json file:
"start": "ng serve --proxy-config proxy.conf.json"
The HTTP call from my app component:
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
Lastly to run my app, I'd have to use npm start
or ng serve --proxy-config proxy.conf.json
Solution 2:
You can also try the fetch
function and the no-cors
mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.
import { from } from 'rxjs';
// ...
result = from( // wrap the fetch in a from if you need an rxjs Observable
fetch(
this.baseurl,
{
body: JSON.stringify(data)
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'no-cors'
}
)
);
Solution 3:
If you are like me and you are using a local SMS Gateway server and you make a GET request to an IP like 192.168.0.xx you will get for sure CORS error.
Unfortunately I could not find an Angular solution, but with the help of a previous replay I got my solution and I am posting an updated version for Angular 7 8 9
import {from} from 'rxjs';
getData(): Observable<any> {
return from(
fetch(
'http://xxxxx', // the url you are trying to access
{
headers: {
'Content-Type': 'application/json',
},
method: 'GET', // GET, POST, PUT, DELETE
mode: 'no-cors' // the most important option
}
));
}
Just .subscribe like the usual.
Solution 4:
Make the header looks like this for HttpClient in NG5:
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'apikey': this.apikey,
'appkey': this.appkey,
}),
params: new HttpParams().set('program_id', this.program_id)
};
You will be able to make api call with your localhost url, it works for me ..
- Please never forget your params columnd in the header: such as params: new HttpParams().set('program_id', this.program_id)