Búsqueda de sitios web

typescript - ¿Cómo arreglar Cannot GET/en Angular al actualizar la página?


Soy nuevo en el mundo de Angular. Seguí la guía de Angular.io para enrutar mi aplicación y sus muchas páginas. El problema que tengo es cuando presiono el botón de actualizar en el navegador. Aparece un "Cannot GET /dashboard". He estado investigando sobre este problema y sí tengo el href="/" en su lugar.

Este es mi archivo de enrutamiento

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },

  { path: '**', redirectTo: '', pathMatch: 'full' }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes,
      {
        enableTracing: false
      }
    )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Como se mencionó antes, puedo acceder a la URL pero cuando refresco la página obtengo el "Cannot GET /dashboard". ¿Hay algo especial que necesite hacer para solucionar este problema? ¿Cómo solucionar Cannot GET/en Angular al refrescar la página?

Respuesta #1

Tu servidor necesita estar configurado para devolver la página HTML base sin importar la URL, para que el enrutador del lado del cliente pueda entonces ver /dashboard y encargarse desde allí. De lo contrario, cuando vayas directamente a /dashboard tu servidor pensará que le estás pidiendo una página de dashboard.

Podrías lograr esto en IIS usando reescrituras de URL. Aquí hay un ejemplo de https://blog.angularindepth.com/deploy-an-angular-application-to-iis-60a0897742e7:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="./index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Otra opción son las URLs basadas en hash, lo cual se puede lograr de esta manera:

RouterModule.forRoot(routes, { useHash: true })

Esto funciona porque el servidor no ve la parte del hash de la URL. Consulta https://angular.io/guide/router para más detalles.

Respuesta #2

Uso Nodejs para servir archivos de Angular, luego he agregado la siguiente parte de código a serve.js y entonces funcionó.

app.route('/*').get(function (req, res) {
  return res.sendFile(path.join(staticRoot + 'index.html'));
});

Obtengo este contenido de aquí

Si utilizas Nginx o Apache para servir archivos, debes usar URLRewrite para redirigir a index.html. El servidor redirige al cliente a index.html y este importará Angular y RoutingModule manejará la navegación.

El contenido de mi serve.js es:

// index.html and its contents are inside the `html` folder
// and the server.js is located on the same path as the `html` folder.
var express = require('express'),
  path = require('path'),
  fs = require('fs');
var compression = require('compression');
var app = express();
var staticRoot = __dirname + '/html/';
var env = process.env.NODE_ENV || 'production';

app.set('port', (process.env.PORT || 3002));

app.use(compression());
/* other middleware */

/* place any backend routes you have here */

app.use(function (req, res, next) {
  //if the request is not html then move along
  var accept = req.accepts('html', 'json', 'xml');
  if (accept !== 'html') {
    return next();
  }
  // if the request has a '.' assume that it's for a file, move along
  var ext = path.extname(req.path);
  if (ext !== '') {
    return next();
  }
  fs.createReadStream(staticRoot + 'index.html').pipe(res);
});

app.use(express.static(staticRoot));

/**
* Redirect to index.html
*/
app.route('/*').get(function (req, res) {
  return res.sendFile(path.join(staticRoot + 'index.html'));
});


app.listen(app.get('port'), function () {
  console.log('app running on port', app.get('port'));
});