简体   繁体   中英

Building an API with node and express, how to get json data from a url?

I'm building an API for a SPA built with Angular 2, for this app I have a stand alone API and than an Angular 2 app. So they are on built on two separate node.js servers. I'm using node.js and express along with 'express-connection' and 'mysql' modules to build a secure API to handle login and registration with JWT's (json web tokens), along with other tasks of course. So I've successfully built this API so I can access data with my Angular 2 app via a URL. I can use the URL 'localhost:3000/data' to access a json data object from my Angular 2 app running on 'localhost:3001/'. However, I also need the API to have access to this data object (an array of users) once the data becomes available. What is the best way to approach/accomplish this task? The only way I can think of now is to have a setTimeout function that waits for the app to load than uses an http get to grab the data from the url. There must be a cleaner way of accomplishing this task. Heres some code I have working, basically a simple node server running express. I'm somewhat new with building API's and Angular 2 concepts so any help is greatly appreciated.

app.js

/** Dependencies **/
var logger          = require('morgan'),
    cors            = require('cors'),
    http            = require('http'),
    express         = require('express'),
    errorhandler    = require('errorhandler'),
    dotenv          = require('dotenv'),
    bodyParser      = require('body-parser');


/** Setup **/
var app = express();

dotenv.load();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.use(function(err, req, res, next) {
  if (err.name === 'StatusError') {
    res.send(err.status, err.message);
  } else {
    next(err);
  }
});

if (process.env.NODE_ENV === 'development') {
  app.use(logger('dev'));
  app.use(errorhandler())
}

/** Requires **/
require('./config/sql.js')(app);
require('./config/routes.js')(app);

/** Port **/
var port = process.env.PORT || 3001;

http.createServer(app).listen(port, function (err) {
  console.log('listening in http://localhost:' + port);
});

routes.js

// routes.js
module.exports = function(app) {
    var query = require('./query.js')(app);

  app.get('/data', function(req, res) {
    query.getData(req,res);
  });

};

sql.js

var connection = require('express-myconnection');
var mysql = require('mysql');

module.exports = function(app){
    app.use(
        connection(mysql,{
            host    : 'localhost',
            user    : 'root',
            password: ‘password’,
            port    :  3306,
            database: ‘my_project’
        }, 'request')
    );
};

query.js

// DB Queries
module.exports = function(app){
    return {
        getData: function(req, res) {
            req.getConnection(function(err,connection){
                connection.query('SELECT * FROM users',function(err,rows){
                    // console.log("success: ", rows);
                    res.json(rows);
                });
            });
        }
    }
};

user.js

setTimeout(function(){
    // http.get function to call to API and grab data and create variable 
},500);

// this is where I need an array of users that I get from a mysql database for login and registration logic  
var users = [];

I'm not sure I got why you need the Angular code to talk to a different UrL but I would write the server code to take the requests from Angular and then internally reach out to the other API to get the data required. Basically use the node server to act like a proxy to reach the other API.

jfriend00 is right in his comment, this is a question of asynchronous calls.

You are looking for the initial requests to kick off the following: Frontend Request > NodeJS API > Database Query

And the response to fulfill and return promises to create a response chain in the reverse order: Database Response > NodeJS API > Frontend Response

You are probably looking for the angular function $http.get with .then() to perform your frontend calls. But you also need an asynchronous function to request the data from within the API or a database instance, then provide it on an endpoint that the frontend can consume. For that you need a promise or callback in your server-side code as listed in jfriend00's comment.

Consider working on just your NodeJS API until you can achieve the response and requests you need, and build out your frontend with Angular later. The users.js file is a fine endpoint to start on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM