A
A
Adel Khalitov2019-01-22 16:32:12
Angular
Adel Khalitov, 2019-01-22 16:32:12

Why doesn't angular redirect but try to load html?

Nodejs backend - express, passport.
Frontend angular.

//Настроенные роуты для angular
app.use('/', express.static(path.join(__dirname, '/dist/practice/')));
app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '/dist/practice/index.html'));
});
app.use('/', router);

//Обработчик post запроса на сервере (Как во всех гуидах)
router.post('/login', (req, res, next) => {
    passport.authenticate('local', {
        successRedirect : '/profile',
        failureRedirect : '/error',
        failureFlash : true
    })(req, res, next);
});

//Сервис который обрабатывает запросы с клиента (angular)
headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })

postData(user) {
      return this.http.post('/login', user, httpOptions);
  }

//Функция вызванная в компоненте
  onSubmit(){
      this.httpService.postData(JSON.stringify(this.user))
        .subscribe(data=>{
          console.log(data);
          this.done=true;
        },
        error => console.log(error)
      );
  }

//Сама форма
<section class="login">
  <div class="wrapper">
    <form class="example-form" (ngSubmit)="onSubmit()" #userform="ngForm">
      <h1>Зарегистрируйтесь сейчас</h1>
      <mat-form-field class="example-full-width">
        <input matInput [(ngModel)]="user.email" name="email" type="email" placeholder="Email">
        <mat-error *ngIf="">
          Email is <strong>required</strong>
        </mat-error>
      </mat-form-field>

      <mat-form-field class="example-full-width">
        <input matInput [(ngModel)]="user.password" name="password" type="password" placeholder="Password" >
      </mat-form-field>
      <div *ngIf="done">
          <div>Получено от сервера:</div>
          <div>Имя: {{receivedUser.email}}</div>
          <div>Возраст: {{receivedUser.password}}</div>
      </div>
      <button mat-raised-button type="submit" color="primary">Регистрация</button>
    </form>
    <p class="lead">Уже зарегистрированы? <a href="#" (click)="openBottomSheet()">Войти</a></p>

  </div>
</section>

Post requests are received on the server, processed, but an error is returned, and for obvious reasons, the redirect does not occur.
The error occurs on the client in the main.adeca9df8fe2d81d2855.js file.
e {headers: t, status: 200, statusText: "OK", url: "http://localhost:3000/profile", ok: false, …}

If you open the error, then:
error: {error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "<!doctype html>↵<html lang="en">↵<head>↵

Also the message itself:
message: "Http failure during parsing for http://localhost:3000/profile"

Why is he parsing it? What to do so that it does not parse the file, but follow the link?
PS: By */profile routers are configured for Angular.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2019-01-22
@SaveLolliPoP

1. Angular won't redirect. It doesn't work like that. It uses XmlHttpRequest under the hood, and XHR works like this in your case: makes a request -> gets a redirect from the server -> goes to the redirect address -> fetches the received response at this address and returns angular. Angular tries to parse the received response. And it expects to receive JSON, but it receives HTML, so it gives an error
2. this.httpService.postData(JSON.stringify(this.user)). Here it is not entirely clear why the user turns into a string and then the string fasts. Usually a JSON object is fasted immediately. Unless there's some wild game on the server. But it's better to solve the issue by posting a JSON object, not a string. You will suffer less
Now for the supply of redirects on the server side. SPAs don't work like that. The server does not deal with redirects. It's not his job. The server's job is to return a JSON response and HTTP status 200 if it can return what is expected of it. And an error otherwise. Here are more details https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
In general, if you want, not to be very upset because of the stupid Angular (and any other SPA framework), then it is advisable to familiarize yourself and start using oAuth or JWT.
If you have read up to this point and said "well, you are in the bath with your advice, I want it to be redirected like normal boys", then you can do it like this:

import { tap } from 'rxjs/operators';

return this.http.post('/login', user, {observe: 'response', responseType: 'text'}).pipe(
  tap(response => {
    location.href = response.url;
  })
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question