в бэкенде nodejs я добавил этот код к server.js
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
но в angularjs 2 клиентской стороне в google chrome бросает эту ошибку
XMLHttpRequest cannot load http://localhost:8080/team. 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. The response had HTTP status code 405.
это служебный код для angular2, который я использую
export class DataService {
// URL to web api
constructor(private http: Http, private _configuration: Configuration,private team:Team) {
//this.actionUrl = _configuration.ServerWithApiUrl;
this.actionUrl = "http://localhost:8080/team";
}
private actionUrl: string;
addData(postData: Team): Observable<Team[]> {
//let body = JSON.stringify({ Team });
this.team = postData;
console.log(this.team);
let body = JSON.stringify({ postData });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.actionUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
ОБНОВЛЕНО:
Для вашего нового сообщения об ошибке: Angular2 - нижний корпус заголовков. Обновите свой сервер, чтобы принять content-type
.
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, content-type, Accept");
Вы не можете отправить сообщение на этот URL: http://posttestserver.com/post.php?dir=anyNameYouWillFind
И можете видеть ваши сообщения там: http://posttestserver.com/data/
Просмотрите год, месяц, день и любойNameYouWillFind..
OLD:
вы должны прикрепить свой URL-адрес!
this.http.get(' http ://localhost: 8080/v1_user/45646/team');
Исправлено, добавив это в backend node.js
// access control --> allowed all origin
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
})
.options('*', function(req, res, next){
res.end();
})
;