如何用离子调用其api rest symfony的URL

问题描述 投票:0回答:1

我已经在symfony中开发了我的api脚本,并与邮递员进行了一些测试,一切都很好,现在我正在与ionic一起在移动应用程序的前端部分和身份验证部分工作,我想知道如何使用我的api rest的url登录名。当我测试登录表单时,控制台中出现一个错误,向我显示net :: ERR_CONNECTION_REFUSED,另一个错误是:XMLHttpRequest无法加载http://127.0.0.1:8000/auth-tokens。请求的资源上不存在“ Access-Control-Allow-Origin”标头。

身份验证控制器

     /**
 * @Rest\View(statusCode=Response::HTTP_CREATED, serializerGroups={"auth-token"})
 * @Rest\Post("/auth-tokens")
 */
public function postAuthTokensAction(Request $request)
{
    $credentials = new Credentials();
    $form = $this->createForm(CredentialsType::class, $credentials);

    $form->submit($request->request->all());

    if (!$form->isValid()) {
        return $form;
    }

     $em = $this->getDoctrine()->getManager();

    $user = $em->getRepository("DoctixUserBundle:User")
        ->findOneByUsername($credentials->getLogin());

    if (!$user) { // L'utilisateur n'existe pas
        return $this->invalidCredentials();
    }

    $encoder = $this->get('security.password_encoder');
    $isPasswordValid = $encoder->isPasswordValid($user, $credentials->getPassword());

    if (!$isPasswordValid) { // Le mot de passe n'est pas correct
        return $this->invalidCredentials();
    }

    $authToken = new AuthToken();
    $authToken->setValue(base64_encode(random_bytes(50)));
    $authToken->setCreatedAt(new \DateTime('now'));
    $authToken->setUser($user);

    $em->persist($authToken);
    $em->flush();

    return $authToken;
}

private function invalidCredentials()
{
    return \FOS\RestBundle\View\View::create(['message' => 'Invalid credentials'], Response::HTTP_BAD_REQUEST);
}

Ionic Html页面

<ion-app>
  <ion-header translucent>
    <ion-toolbar>
      <ion-title>Se Connecter</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content fullscreen>
    <form>
      <ion-list lines="full" class="ion-no-margin ion-no-padding">
        <ion-item>
          <ion-label position="stacked">Nom d'utilisateur  <ion-text color="danger">*</ion-text></ion-label>
          <ion-input required type="text" name="username" [(ngModel)]="username"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label position="stacked">Mot de passe <ion-text color="danger">*</ion-text></ion-label>
          <ion-input required type="password" name="password" [(ngModel)]="password" ></ion-input>
        </ion-item>

      </ion-list>

      <div class="ion-padding">
        <ion-button size="small" type="submit" (click)="authenticate()" class="ion-no-margin">Se Connecter</ion-button>
        <ion-button size="small" routerLink="/register" routerDirection="forward" class="ion-no-margin">S'inscrire</ion-button>
      </div>
    </form>
  </ion-content>
</ion-app>

Ionic脚本控制器

import { Component } from '@angular/core';
import {NavController} from '@ionic/angular';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
// import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
@Injectable()
export class HomePage {

  username: any;
  password: any;
  response: any;
  constructor(public navCtrl: NavController, private http: Http) {
  }

  login() {
            // this.authenticate();
  }

  authenticate() {
    const url     = 'http://127.0.0.1:8000/auth-tokens';
    const body     = new URLSearchParams();
    console.log('Username: ' + this.username);
    console.log('Password: ' + this.password);
    body.append('login', this.username);
    body.append('password', this.password);
    const headers = new Headers(
        {'Content-Type': 'application/json'}
        );
    headers.append('Accept', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Headers', '*');
    headers.append('Access-Control-Allow-Credentials', 'true');
    const options = new RequestOptions({headers});

    const localData = this.http
        .post(url, body.toString(), options).pipe(map(
            (data) => data.json())
        );
    localData.subscribe(res => {
      this.response = res;
      console.log(this.response);
    });
  }

感谢

angular api symfony ionic-framework
1个回答
0
投票

您似乎正面临CORS问题。

© www.soinside.com 2019 - 2024. All rights reserved.