将角度应用程序连接到服务器

时间:2019-03-08 10:27:30

标签: mysql node.js angular api express

我是angular的初学者,我用Rest Crud API和我的数据库Mysql创建了我的Nodeserver,并且想将其与我的angular(ngx nebular)项目关联,但是我做不到,谢谢您的帮助。

这是app.js

 var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var cors = require('cors');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var user=require('./model/user');
var api = require('./routes/api'); 

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/user',api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

`

2 个答案:

答案 0 :(得分:1)

您应该侦听所有GET请求,并仅以文件形式发送index.html,该文件实际上应该包含您的Angular SPA。像这样:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));    
});

您可以查看Express文档:http://expressjs.com/fr/api.html#res.sendFile

答案 1 :(得分:0)

您需要加载mysql库以访问其功能。您还需要为首页设置一个GET处理程序,并为其分配路由。

1)引入MySQL @ app.js

const mysql = require('mysql');

// ... other stuff here ...

// the mysql.createConnection function takes in a configuration object 
// this contains host, user, password and the database name.
const db = mysql.createConnection ({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'latelist'
});

// connect to database
db.connect((err) => {
    if (err) {
        throw err;
    }
    console.log('Connected to database');
});
global.db = db;

2)路由yourHomepageFunction

在您的情况下,我们已经在indexRouter.js中进行路由,因此,请务必在app.js中的第3步之前进行此操作。

app.use('/', indexRouter);

3)为/

分配GET处理程序

最后,请确保在app.js中的某个位置为首页设置GET处理程序:

app.get('/', yourHomepageFunction);

为了后代,以下是indexRouter.js的示例:

module.exports = {
    yourHomepageFunction: (req, res) => {
        res.render("homepage.ejs", {
             // Stuff here such as passing title variables, etc
        });
    }
};