Ошибка кросс-оргина в Google Chrome для вызова API

0

в бэкенде 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);

    }
Теги:
angular

2 ответа

1

ОБНОВЛЕНО:

Для вашего нового сообщения об ошибке: 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');

  • 0
    Вы имеете в виду, я должен добавить " localhost: 8080 / v1_user / 45646 / team " этот URL на стороне клиента справа ??
  • 1
    Пожалуйста, опубликуйте ваш метод Angular2 get.
Показать ещё 7 комментариев
0

Исправлено, добавив это в 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();
})
;

Ещё вопросы

Сообщество Overcoder
Наверх
Меню