kostyaostapuk
@kostyaostapuk

Ошибка POST запроса в Angular 5?

Failed to load https://github.com/login/oauth/access_token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '127.0.0.1:4200' is therefore not allowed access. The response had HTTP status code 404.

Пытаюсь выполнить следующий запрос
getToken(){
    this.route.queryParams.subscribe(params=>{
      this.githubCode=params['code'];
      localStorage.setItem('githubCode',this.githubCode);

      let headers = new Headers();
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      headers.append("cache-control", "no-cache");
      let body={
        client_id: this.clientID,
        client_secret: this.clientSecret,
        code: localStorage.getItem('githubCode'),
        redirect_uri: this.redirectURI
      }
      let url='https://github.com/login/oauth/access_token';
      console.log(body);
      this._http.post(url,body, {headers})
        .subscribe(res => console.log(res.json()));
    });

  }


Сервер у меня запущен и код сервера:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const http = require('http');
const app = express();

app.use(cors({
  origin: 'http://127.0.0.1:4200',
  credentials: true
}));


app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

// API file for interacting with MongoDB
const api = require('./src/server/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'src/index.html'));
});

//Set Port
const port = process.env.PORT || '4200';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`Running on localhost:${port}`));
  • Вопрос задан
  • 703 просмотра
Пригласить эксперта
Ответы на вопрос 2
@kacheleff
fullstack developer
Дело в том, что перед тем, как отправить непростой запрос, сначала будет отправлен OPTIONS запрос. Нужно отдавать правильный ответ на этот запрос, иначе браузер будет блокировать ответ сервера. Пример можно увидеть здесь
Ответ написан
Комментировать
@dotajax
Вы отправляете запрос на https://github.com/login/oauth/access_token, но он не разрешает доступ, так как отсутствуют заголовки типа Access-Control-Allow. Также в ошибке указан код ответа страницы 404, что свидетельствует о том, что страницы не найдено.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы