URL, запрошенные через Http на сервере, должны быть абсолютными - PullRequest
0 голосов
/ 27 мая 2018

Я создал угловое универсальное приложение с angular2, где я запрашиваю / обслуживание категории.

this.hsService.getCategories(AppConstants.BASE_URL_GET_CATGORIES).subscribe(
  resp => {
    if (resp !== null) {
      console.log('response is not null');
    }else {
      console.log('response is null');
    }
  },
  err => {
    console.log('error');
    that.categories = that.Categories();
  }
);

Но я получил эту ошибку ниже ошибки.Но не понял почему?

ОШИБКА: URL-адреса, запрошенные через Http на сервере, должны быть абсолютными.URL: / category at validateRequestUrl (D: \ Myprojects \ angular universal \ ciel \ node_modules \ @angular \ platform-server \ bundles \ platform-server.umd.js: 99: 15 в новом ZoneMacroTaskConnection (D: \ Myprojects \ angular universal\ ciel \ node_modules \ @angular \ platform-server \ bundles \ platform-server.umd.js: 226: 9) в ZoneMacroTaskBackend.createConnection (D: \ Myprojects \ угловой универсальный \ ciel \ node_modules \ @angular \ platform-server \bundles \ platform-server.umd.js: 262: 16) на httpRequest (D: \ Myprojects \ angular universal \ ciel \ node_modules \ @angular \ http \ bundles \ http.umd.js: 1833: 20) на Http.request(D: \ Myprojects \ angular universal \ ciel \ node_modules \ @angular \ http \ bundles \ http.umd.js: 1943: 34) на Http.get (D: \ Myprojects \ angular universal \ ciel \ node_modules \ @angular \)http \ bundles \ http.umd.js: 1957: 21) в n.getCategories (D: \ Myprojects \ angular universal \ ciel \ dist-server \ main.bundle.js: 1: 26301) в n.XV61.n.getCategories (D: \ Myprojects \ angular universal \ ciel \ dist-server \ main.bundle.js: 1: 24428) в n.XV61.n.ngOnInit (D: \ Myprojects \ angular universal \ ciel \ dist-server \ main.bundle.js: 1: 24346) на checkAndUpdateDirectiveInline (D: \ Myprojects \ angular universal \ ciel \ node_modules \ @angular \ core \ bundles \ core.umd.js: 10875: 19)

Кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 28 мая 2018

При рендеринге на стороне сервера для любых HTTP-вызовов требуется абсолютный URL-адрес.

Вы можете либо

  1. Использовать абсолютные URL-адреса для HTTP-запросов
  2. Вставитьисходный URL и префикс к базовому URL на стороне сервера

В ответах на вопрос на этот вопрос можно указать несколько вариантов: 2 .

Я бы лично предложил настроить токен инъекции, который дает вам источник сервера, и добавить его к базовому URL-адресу, используя перехватчики HTTP:

Добавить класс перехватчика HTTP:

import { Injectable, Inject, Optional } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

@Injectable()
export class UniversalInterceptor implements HttpInterceptor {

  constructor(@Optional() @Inject('serverUrl') protected serverUrl: string) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    const serverReq = !this.serverUrl ? req : req.clone({
      url: `${this.serverUrl}${req.url}`
    });

    return next.handle(serverReq);

  }
}

Добавить его вмассив провайдеров серверного модуля:

providers: [
{
  provide: HTTP_INTERCEPTORS,
  useClass: UniversalInterceptor,
  multi: true
}

В конфигурации на стороне сервера (в этом примере выражается) укажите токен с URL-адресом источника сервера:

let protocol = 'http';
if (process.env.NODE_ENV == 'production') {
   protocol = 'https'
}

app.engine('html', (_, options, callback) => {
  let engine = ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'serverUrl',
        useValue: `${protocol}://${options.req.get('host')}`
      }
    ]
  });

  engine(_, options, callback)
})
0 голосов
/ 28 мая 2018

Ошибка: URL-адреса, запрошенные через Http на сервере, должны быть абсолютными.

Похоже, что AppConstants.BASE_URL_GET_CATGORIES - это undefined или неверный http URL.

Я думаю, вам нужно ввести URL-адрес источника для создания абсолютного пути

export function createTranslateLoader(http: Http, @Inject('AppConstants.BASE_URL_GET_CATGORIES') originUrl: string) {
  return new TranslateHttpLoader(http, originUrl);
}
...