angular: what's wrong with the http headers in angular 2 using typescript
I found several documents telling me to set the headers by the code below.
var tokenHeader = new Headers();
tokenHeader.append('token', 'somevalue');
var options = new RequestOptions({
method: RequestMethod.Get,
url: 'http://localhost:8080/v1/users',
headers: tokenHeader
});
var req = new Request(options);
this.http.request(req)
.subscribe((res: Response) => {
<do something>
});
when I look at the console when sending this request, the request headers look like:
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ja;q=0.6,zh-CN;q=0.4,zh;q=0.2
Access-Control-Request-Headers:token
Access-Control-Request-Method:GET
...
I can find “token” in Access-Control-Request-Headers, but, where is my “somevalue”?, by using “curl” command, the request headers look like the code below and it works well.
Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> Referer: rbose
> token: <somevalue>
> Cache-Control: no-cache
Also having this header problem, I receive the error message all the time even though I set the “w.Header().Set(“Access-Control-Allow-Origin”, “*”)” in my server side.(no error occurs if I don’t add headers in the request)
XMLHttpRequest cannot load http://localhost:8080/v1/users. 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:8000' is therefore not allowed access. The response had HTTP status code 404.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 23
- Comments: 30 (4 by maintainers)
Please use @CrossOrigin on the backend side in Java Spring boot controller (either class level or method level) as the solution for Chrome error’No ‘Access-Control-Allow-Origin’ header is present on the requested resource.’
This solution is working for me 100% …
@CrossOrigin @Controller public class UploadController {
----- OR -------
@CrossOrigin(origins = “http://localhost:3000”, maxAge = 3600) @RequestMapping(value = “/loadAllCars”) @ResponseBody public List<Car> loadAllCars() {
Ref: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
CORS doesn’t come into play when using curl - it is only browser’s mechanism. At this is a mechanism on a browser level, not a framework level. More info: http://www.html5rocks.com/en/tutorials/cors/
I had the same issue, client side --> angular 5 server side --> Nodejs v9.8.0
I have added cors to the server app
npm install cors --save
then imported:
const cors = require('cors');
Then enabled the middleware :
app.use(cors());
Thats it, now it is working fine with no issue.
In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn’t really an option. So, I created a proxy.conf.json file to act as a proxy server.
Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
below is my proxy.conf.json file
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 like below
now, the http call from my app component is as follows
Lastly to run my app, I’d have to use npm start or ng serve --proxy-config proxy.conf.json
I had the same issue, client side --> angular 5 server side --> Nodejs v9.8.0
I have added cors to the server app npm install cors --save
then imported: const cors = require(‘cors’);
Then enabled the middleware : app.use(cors());
Thats it, now it is working fine with no issue.
is adding @CrossOrigin works
you just need a proxy (webpack dev server has one) to redirect requests from 3000 to 8080 port.
In rest app set cors related settingsIn case rest service and angular both are in same host and port this error will not come else it is common security error .
i have to part of code in two place when i was building my application… one work with no error, another delegate to CORS, why is that?
Direct Call: Note: no fancy stuff used, just simple call: import { Component, OnInit } from ‘@angular/core’; import { HttpClient } from ‘@angular/common/http’;
@Component({ selector: ‘app-home’, templateUrl: ‘./home.component.html’, styleUrls: [‘./home.component.css’] }) export class HomeComponent implements OnInit { registerMode = false; values: any;
constructor(private http: HttpClient) { }
ngOnInit() { this.getValues(); }
registerToggle() { this.registerMode = true; }
getValues() { this.http.get(‘http://localhost:60421/api/Nest/anonymous’) .subscribe(data => { this.values = data; }); }
cancelRegisterMode(registerMode: boolean) { this.registerMode = registerMode; } }
From Service: (Cause Cross Origin Error) Note: i used http header… first i though because on server i used authorize attribute it cause error, then i found out even calling to a method with [AllowAnonymous] cause same issue to import { Component, OnInit } from ‘@angular/core’; import { BasePlace } from ‘src/_models/entities/basePlace’; import { AlertifyService } from ‘…/_services/alertify.service’; import { NestService } from ‘…/_services/nest.service’;
@Component({ selector: ‘app-property-list’, templateUrl: ‘./property-list.component.html’, styleUrls: [‘./property-list.component.css’] }) export class PropertyListComponent implements OnInit { basePlaces: BasePlace[];
constructor(private nestService: NestService, private alertify: AlertifyService) { }
ngOnInit() { this.loadUsers(); }
loadUsers() { this.nestService.getNests().subscribe((besePlaces: BasePlace[]) => { this.basePlaces = besePlaces; }, error => { this.alertify.error(error); }); }
}
import { Injectable } from ‘@angular/core’; import { environment } from ‘src/environments/environment’; import { HttpClient, HttpHeaders } from ‘@angular/common/http’; import { Observable } from ‘rxjs’; import { BasePlace } from ‘src/_models/entities/basePlace’; import { map } from ‘rxjs/operators’; import { ModelHelper } from ‘src/_utility/modelHelper’; import { ModelType } from ‘src/_utility/modelType’;
@Injectable({ providedIn: ‘root’ }) export class NestService { baseUrl = environment.apiUrl;
constructor(private http: HttpClient) { } getNests(): Observable<BasePlace[]> { return this.http.get(this.baseUrl + ‘nest/anonymous’, this.jwt()) .pipe( map(basePlace => ModelHelper.toArray(basePlace as any, ModelType.BasePlace) as BasePlace[]) ); }
private jwt() { const token = localStorage.getItem(‘token’); if (token) { return this.createRequestOptions(token); } }
private createRequestOptions(token: string) { const headers = new HttpHeaders({ Authorization: 'Bearer ’ + token }); headers.append(‘Content-Type’, ‘application/json’); const options = { headers }; return options; } }
2:60421/api/nest/anonymous:1 GET http://localhost:60421/api/nest/anonymous 401 (Unauthorized) properties:1 Access to XMLHttpRequest at ‘http://localhost:60421/api/nest/anonymous’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
— You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.
actually, you can do that without Cors module too, please check the below middleware for Nodejs,