如何在node . js中处理angular2路径

时间:2021-11-22 23:06:45

I am working on a NodeJS app with Angular2. In my app, I have a home page and search page. For home page I have an HTML page that will render for the localhost:3000/ and from home page user navigate to search i.e localhost:3000/search page that I handled by angular2 routes.

我正在用Angular2开发一个NodeJS应用程序。在我的应用中,我有一个主页和搜索页面。对于主页,我有一个HTML页面,它将为localhost:3000/呈现,并且从主页用户导航到搜索I。e localhost:3000/search页面,我通过angular2路由处理。

I don't have the page for the search page its view render by the angular2. But when I directly hit localhost:3000/search as I don't have this routing in my node app it gives the error.

我没有搜索页面的页面,它的视图由angular2呈现。但是当我直接点击localhost:3000/search时,因为我的节点应用程序中没有这个路由,它会产生错误。

I don't know How to handle this in node app?

我不知道如何在node app中处理这个?

3 个解决方案

#1


24  

If you enter localhost:3000/search directly in the browser navigation bar, your browser issues an request to '/search' to your server, which can be seen in the console (make sure you check the 'Preserve Log' button).

如果您直接在浏览器导航栏中输入localhost:3000/search,您的浏览器会向您的服务器发出一个“/search”请求,这可以在控制台中看到(请确保您检查了“Preserve Log”按钮)。

Navigated to http://localhost:3000/search

If you run a fully static server, this generates an error, as the search page does not exist on the server. Using express, for example, you can catch these requests and returns the index.html file. The angular2 bootstrap kicks-in, and the /search route described in your @RouteConfig is activated.

如果您运行一个完全静态的服务器,这会产生一个错误,因为在服务器上不存在搜索页面。例如,使用express,您可以捕获这些请求并返回索引。html文件。angular2引导启动,并激活@RouteConfig中描述的/搜索路径。

// example of express()
let app = express();
app.use(express.static(static_dir));

// Additional web services goes here
...

// 404 catch 
app.all('*', (req: any, res: any) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.status(200).sendFile(index_file);
});

#2


1  

You need to use HashLocationStrategy

您需要使用HashLocationStrategy。

import { LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(AppComponent, [
 ROUTER_PROVIDERS,
 provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

In your bootstrap file.

在你的引导文件。

If you want to go with PathLocationStrategy ( without # ) you must setup rewrite strategy for your server.

如果您想使用PathLocationStrategy(没有#),您必须为您的服务器设置重写策略。

#3


0  

I've been digging this topic for quite a time , and try a lot of method that don' work . If you are using angular-cli and with express , I found a solution if the chosen answer doesn't works for you .

我一直在钻研这个课题,尝试了很多方法。如果您正在使用angular-cli和express,我找到了一个解决方案,如果选择的答案不适合您。

Try this node module : express-history-api-fallback

尝试这个节点模块:express-history-api-fallback

[ Angular ] Change your app.module.ts file , under @NgModule > imports as following :

改变你的app.module。ts文件,@NgModule >下导入如下:

RouterModule.forRoot(routes), ...

This is so called : " Location Strategy "

这就是所谓的“定位策略”

You probably were using " Hash Location Strategy " like this :

你可能在使用“散列位置策略”,比如:

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

[ Express & Node ] Basically you have to handle the URL properly , so if you want call "api/datas" etc. that doesn't conflict with the HTML5 Location Strategy .

[Express & Node]基本上你必须正确处理URL,所以如果你想调用“api/datas”等,这与HTML5的定位策略并不冲突。

In your server.js file ( if you used express generator , I've rename it as middleware.js for clarity )

在你的服务器。js文件(如果您使用express generator,我将它重命名为中间件。js清晰)

Step 1. - Require the express-history-api-fallback module .

步骤1。-需要expresshistory -api-fallback模块。

const fallback = require('express-history-api-fallback');

Step 2 . You may have a lot of routes module , sth. like :

步骤2。您可能有很多路由模块,例如:

app.use('/api/users, userRoutes);
app.use('/api/books, bookRoutes); ......
app.use('/', index); // Where you render your Angular 4 (dist/index.html) 

Becareful with the order you are writing , in my case I call the module right under app.use('/',index);

注意您所编写的顺序,在我的例子中,我在app.use('/',index)下调用模块;

app.use(fallback(__dirname + '/dist/index.html'));

* Make sure it is before where you handle 404 or sth. like that .

*确保在你处理404或类似的东西之前。

This approach works for me : ) I am using EAN stack (Angular4 with cli , Express , Node )

这种方法对我很有效:)我正在使用EAN堆栈(Angular4与cli、Express、Node)

#1


24  

If you enter localhost:3000/search directly in the browser navigation bar, your browser issues an request to '/search' to your server, which can be seen in the console (make sure you check the 'Preserve Log' button).

如果您直接在浏览器导航栏中输入localhost:3000/search,您的浏览器会向您的服务器发出一个“/search”请求,这可以在控制台中看到(请确保您检查了“Preserve Log”按钮)。

Navigated to http://localhost:3000/search

If you run a fully static server, this generates an error, as the search page does not exist on the server. Using express, for example, you can catch these requests and returns the index.html file. The angular2 bootstrap kicks-in, and the /search route described in your @RouteConfig is activated.

如果您运行一个完全静态的服务器,这会产生一个错误,因为在服务器上不存在搜索页面。例如,使用express,您可以捕获这些请求并返回索引。html文件。angular2引导启动,并激活@RouteConfig中描述的/搜索路径。

// example of express()
let app = express();
app.use(express.static(static_dir));

// Additional web services goes here
...

// 404 catch 
app.all('*', (req: any, res: any) => {
  console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
  res.status(200).sendFile(index_file);
});

#2


1  

You need to use HashLocationStrategy

您需要使用HashLocationStrategy。

import { LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(AppComponent, [
 ROUTER_PROVIDERS,
 provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

In your bootstrap file.

在你的引导文件。

If you want to go with PathLocationStrategy ( without # ) you must setup rewrite strategy for your server.

如果您想使用PathLocationStrategy(没有#),您必须为您的服务器设置重写策略。

#3


0  

I've been digging this topic for quite a time , and try a lot of method that don' work . If you are using angular-cli and with express , I found a solution if the chosen answer doesn't works for you .

我一直在钻研这个课题,尝试了很多方法。如果您正在使用angular-cli和express,我找到了一个解决方案,如果选择的答案不适合您。

Try this node module : express-history-api-fallback

尝试这个节点模块:express-history-api-fallback

[ Angular ] Change your app.module.ts file , under @NgModule > imports as following :

改变你的app.module。ts文件,@NgModule >下导入如下:

RouterModule.forRoot(routes), ...

This is so called : " Location Strategy "

这就是所谓的“定位策略”

You probably were using " Hash Location Strategy " like this :

你可能在使用“散列位置策略”,比如:

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

[ Express & Node ] Basically you have to handle the URL properly , so if you want call "api/datas" etc. that doesn't conflict with the HTML5 Location Strategy .

[Express & Node]基本上你必须正确处理URL,所以如果你想调用“api/datas”等,这与HTML5的定位策略并不冲突。

In your server.js file ( if you used express generator , I've rename it as middleware.js for clarity )

在你的服务器。js文件(如果您使用express generator,我将它重命名为中间件。js清晰)

Step 1. - Require the express-history-api-fallback module .

步骤1。-需要expresshistory -api-fallback模块。

const fallback = require('express-history-api-fallback');

Step 2 . You may have a lot of routes module , sth. like :

步骤2。您可能有很多路由模块,例如:

app.use('/api/users, userRoutes);
app.use('/api/books, bookRoutes); ......
app.use('/', index); // Where you render your Angular 4 (dist/index.html) 

Becareful with the order you are writing , in my case I call the module right under app.use('/',index);

注意您所编写的顺序,在我的例子中,我在app.use('/',index)下调用模块;

app.use(fallback(__dirname + '/dist/index.html'));

* Make sure it is before where you handle 404 or sth. like that .

*确保在你处理404或类似的东西之前。

This approach works for me : ) I am using EAN stack (Angular4 with cli , Express , Node )

这种方法对我很有效:)我正在使用EAN堆栈(Angular4与cli、Express、Node)