MEAN:nodejs server for Angular App -我如何提供angular路由

sg3maiej  于 11个月前  发布在  Node.js
关注(0)|答案(2)|浏览(78)

这里是我的节点server.js,它在项目根目录下,有自己的npm配置。所有的Angular文件都在/client中,因此在ng build之后,dist将在client/dist


的数据

const express = require('express');
const colors = require('colors');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');

const PORT = process.env.port||'3200';

// init "app"
const app = express();

app.use(cors({origin: `http://localhost:4200`}));

// angular entry point
app.use(express.static(path.join(__dirname, 'client/dist')));

//parse incoming data before routes
app.use(bodyParser.json())

// api routes
app.use('/api',require('./api/api'));

// error middleware
app.use(function(err, req, res, next){
    console.log(`${err}`.red.bold)
    res.status(422).send({error: err.message });
});

// listen
app.listen(PORT, function(){
    console.log(`app running on ${PORT}...`.magenta);
});

字符串
当我转到服务器http://localhost:3200/时,我看到了我的angular应用程序。当我转到http://localhost:3200/api/someExpressRoute时,我得到了我的API函数。太好了
现在我需要弄清楚如何服务角路由。例如http://localhost:3200/about是我的角单页应用程序的一部分。但是当我去那个网址时,服务器不知道该怎么做。
如何配置此服务器以将http://localhost:3200/*处理为从索引提供服务的Angular 路由?

zdwk9cvp

zdwk9cvp1#

下面是我如何通过nodejs服务我的angular应用程序:

var express = require('express'),
   path = require('path'),
   fs = require('fs');
var compression = require('compression');
var app = express();
var staticRoot = __dirname + '/';
var env = process.env.NODE_ENV || 'development';

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

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));

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

字符串
在为应用程序提供服务时,确保所有前端dist文件都与此文件位于同一个文件夹中(我称之为index.js

plupiseo

plupiseo2#

使用NodeJs Express服务Angular应用

如果你想使用NodeJ来服务你的angular应用,你需要使用expressJs的res.sendFile()函数来服务你的Angular构建的index.html文件。更多细节请参见文档。
在此之前,你需要确保Express内置的中间件static指向一个包含Angular在编译过程中构建的所有文件的文件夹(通常是前端应用程序的dist文件夹)。

服务Angular 路由

如果你想让你的Angular Router工作,你需要将所有传入的请求重定向到前端。你也可以添加一些验证,比如@Syntactic Fructose建议,来检查请求中的html或文件。

示例

这只是一个基本的例子,

import express, { Request, Response , Application } from 'express';
import path from 'path';
import http from 'http';
import { router } from './path/to/my/api/routes';

const app = express();

const frontendFiles = "path/to/your/frontend/dist/folder";

// Point static middleware to your Angular build
app.use(express.static(frontendFiles));

// Your api routes
app.use('/api', router);

// Do whatever you want like
// app.get('/someStuff', (req, res) => {...}

// Then your last route is
app.get('/*', function(req, res){
  res.sendFile(path.join(frontendFiles, '/index.html'));
});

// Serve your app
const httpServer = new http.Server(app);
const port = 3000;
httpServer.listen(port, function() {
    console.log(`app fire on http://localhost:${port}`);
});

字符串

评论

为了更简单地部署,我建议您使用.env变量作为frontendFiles变量。

相关问题