【问题标题】:Can't set up Angular (6) + MySQL + NodeJS + Express无法设置 Angular (6) + MySQL + NodeJS + Express
【发布时间】:2019-02-28 09:31:12
【问题描述】:

您好,我正面临着这样的生存危机。

谁能给我一个例子,说明如何将我的 Angular(我正在使用 Angular 6)前端与 MySQL 数据库(请不是 NoSQL 示例,有很多)连接,使用节点/快递后端?

周末我一直在阅读,搜索 google、stack、youtube 等,并且有很多示例,但还不足以让我理解。我想不通的是如何在我的前端按下一个按钮,调用我的数据库并让它出现在我的网站上(基本上所有的 CRUD 操作)。

我需要硬代码。我没有任何代码,因为我什至无法想象如何在我的 app.js 中与我的 Angular 组件中的按钮连接以制作对 mysql 数据库的 crud 操作。我真的很困惑。

假设我在 MySQL 中使用 phpmyadmin,并且有一个名为 users 的数据库,1 列包含 user_name,一个值为 Aquiles。有了它,我想阅读、更新、删除。

其他帖子的链接(尽管我几乎搜索了所有帖子)、视频、教程,都是受欢迎的。

感谢您的宝贵时间, 问候。

【问题讨论】:

    标签: mysql node.js angular express


    【解决方案1】:

    我做到了

    回答我自己的问题,如果有任何灵魂因此而绝望,就在这里。

    1。在 phpmyAdmin 或您想要的数据库中创建一个 db 和 table。

    CREATE TABLE IF NOT EXISTS 'tasks' (
    
      'id' int(11) NOT NULL,
      'task' varchar(200) NOT NULL,
      'status' tinyint(1) NOT NULL DEFAULT '1',
      'created_at' datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    
    
    ALTER TABLE 'tasks' ADD PRIMARY KEY ('id');
    ALTER TABLE 'tasks' MODIFY 'id' int(11) NOT NULL AUTO_INCREMENT;
    
    INSERT INTO 'tasks' ('id', 'task', 'status', 'created_at') VALUES
    (1, 'Find bugs', 1, '2016-04-10 23:50:40'),
    (2, 'Review code', 1, '2016-04-10 23:50:40'),
    (3, 'Fix bugs', 1, '2016-04-10 23:50:40'),
    (4, 'Refactor Code', 1, '2016-04-10 23:50:40'),
    (5, 'Push to prod', 1, '2016-04-10 23:50:50');
    

    我是通过阅读这篇文章Creating a RESTful API with Express js, Node js/MySQl - Arjun

    2。后端:服务器 + API 端点

    const express = require('express');
        const mysql = require('mysql');
        const bodyParser = require('body-parser');
        const app = express();
    
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({
            extended: true
        }));
    
        // Connect my db
        var connection = mysql.createConnection({
          host     : 'localhost',
          user     : 'root',
          password : '',
          database : 'dbName'
        });
    
        connection.connect(function(err) {
            if (err) {
              console.error('error connecting: ' + err.stack);
              return;
            }
    
            console.log('connected as id ' + connection.threadId);
        });
    
        app.get('/', function (req, res) {
        res.send('Hello World!');
        });
    
        // Port that will be listened
        app.listen(3000, function () {
          console.log('Example app listening on port 3000!');
        });
    
        // the query
        querie = 'SELECT * FROM tasks';
    
    **THIS IS THE API ENDPOINT FOR THE GET REQUESTS**
    
        app.get('/todos', function (req, res) {
            connection.query(querie, function (error, results, fields) {
                if (error) throw error;
                return res.send({ error: false, data: results, message: 'Todos list.' });
            });
        });
    

    3。角度

    app.component.html 文件

    <button
      (click)="getData()">GET Profile
    </button>
    

    4。 app.component.ts 文件

    import { Component } from '@angular/core';
    import { HttpClient } from "@angular/common/http";
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      constructor (private httpClient:HttpClient){ }
    
      getData(){
        this.httpClient.get('/api/todos')
          .subscribe(
              (data:any[]) => {
                console.log(data);
              }
            )
      }
    }
    

    终于

    现在您需要在一个终端窗口中启动您的 Angular 项目,而在另一个终端窗口中启动服务器。一个将在端口 4200(角度)中,服务器将在 localhost:3000 中,就像我们在 app.js 中配置的那样。

    问题在于,当您通过端口 :4200 从前端发出 get 请求时,会导致错误。它说您的请求正在通过http://localhost:4200/localhost:3000 或与此非常相似的东西(太晚了,我没有记录确切的错误,抱歉)。所以经过一些研究,我遇到了这篇文章https://medium.freecodecamp.org/the-best-ways-to-connect-to-the-server-using-angular-cli-b0c6b699716c,并使用了“代理方法”。

    ,在我的 javascript 控制台中有一个数组,其中包含我的数据库中的所有内容。

    阅读这篇文章可以更清楚地了解所有内容。这是一个非常糟糕的解释(对于高级解释)。

    1. the-best-ways-to-connect-to-the-server-using-angular-cli
    2. same-port-4200-for-both-production-an
    3. stories-proxy
    4. proxy-for-api-calls-for-your-angular-cli-app

    问候。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2017-03-03
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多