UPDATE: So, I'm putting this here because it's more relevant.
I used another example from BobbyHadz and it's much better. https://www.digitalocean.com/community/tutorials/build-a-restful-api-using-node-and-express-4
So, the ONLY thing I've done is this.
I made a connection to the DB for getting PhoneTypes and it's working. I have the ROUTES for CRUD in another file and the REQUIRE for the DB in the routes file and that works, but, what is not working or is out of place, is the data file which contains the RECORDSET (and it's retrieving) is TOO EARLY.
This is in the phoneTypeRoutes.js
const PhoneTypes = require("../../model/phone_types");
const phonetypesdata = require("../../database/phone-types-data");
console.log("PHONE TYPES DATA inside PTROUTE: ", phonetypesdata);
phone-types-data.js is the DATABASE connection.
Then, in index.js, I'm pulling (requiring) the router for phone types like so.
const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
What's happening is this in the console for NODEJS.
[nodemon] starting `node index.js`
PHONE TYPES DATA inside PTROUTE: { phonetypesDataArray: [] } <<-- TOO EARLY
DB CONNECT is: {} <<-- TOO EARLY
Listening on port number: 8000
connected for phonetypes
connected branches of service
connected db-conn
ALL PHONE TYPES RETRIEVED: {
recordsets: [ [ [Object], [Object], [Object] ] ],
recordset: [
{ phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
{ phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
{ phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
],
output: {},
rowsAffected: []
}
RECORDSET PHONETYPES: [
[
{ phone_types_id: 1, phone_type_name: 'CELL', rowCnt: 3 },
{ phone_types_id: 2, phone_type_name: 'HOME', rowCnt: 3 },
{ phone_types_id: 3, phone_type_name: 'WORK', rowCnt: 3 }
]
]
// Those first two lines need to be DOWN here... AFTER the data comes back
Unless I'm missing something...
Here's the DB call which is working phone-types-data.js
const sql = require("mssql");
const env = require("../../environment.js");
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
connectionString:
"Dsn=" +
env.FORMS.DSN.ACCRED +
";Driver=" +
env.FORMS.DRIVER +
";Host=" +
env.FORMS.HOST.LOCAL +
";Database=" +
env.FORMS.DBNAME.ACCRED +
";trusted_connection=" +
env.FORMS.OPTIONS.trustedConnection +
";",
};
const dbConn = new sql.ConnectionPool(config);
let phonetypesDataArray = [];
let query;
query = env.STOREDPROCS.GET.PHONETYPES;
sql
.connect(config)
.then((dbConn) => {
console.log("connected for phonetypes");
dbConn.query(query, (err, data) => {
if (err) {
console.log("Error getting PhoneTypes from Stored Proc: ", err);
sql.close();
}
if (data) {
console.log("ALL PHONE TYPES RETRIEVED: ", data);
phonetypesDataArray.push(data.recordset);
console.log("RECORDSET PHONETYPES: ", phonetypesDataArray);
} else {
let errmsg =
"NO RECORDS RETURNED for " + env.STOREDPROCS.GET.PHONETYPES;
console.log(errmsg);
phonetypesDataArray.push({ error: errmsg });
}
sql.close();
// res.send(recordset);
});
})
.catch((err) => {
console.log("error", err);
errmsg = `"Error Connecting to Database: ", ${err}`;
phonetypesDataArray.push(errmsg);
});
module.exports = { phonetypesDataArray };
I've written a node server app for APIs. I'm calling it from Angular 13. I got the idea from here... https://medium.com/bb-tutorials-and-thoughts/how-to-make-api-calls-in-angular-applications-ab5364cf9533 but my solution is more complicated and I'm getting NOT FOUND on Node when I ping the server URL or call from Angular.
Here's the dumbed down version of the code:
First NODE:
This is server.js
var Service = require('node-windows').Service;
var svc = new Service({
name: 'Node Rest API',
description: 'The nodejs.org example web server.',
script: 'C:\\somedir\\subdir\\nameofsomething\\node-rest-api\\index.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install', function () {
svc.start();
});
svc.install();
This is index.js
const express = require("express");
const path = require("path");
// const mongoose = require('mongoose');
const cors = require("cors");
const bodyParser = require("body-parser");
const sql = require("mssql");
// ROUTES
const noderoutes = require("./node-backend/routes/form21.routes");
const phonetyperoute = require("./node-backend/routes/phoneTypes/phoneTypeRoutes");
const branchesofservice = require("./node-backend/routes/branchesOfService/branchesRoutes");
const app = express();
const enviro = require("./environment");
const createError = require("http-errors");
const { env } = require("process");
const dbconfig = require("./node-backend/database/db-conn");
const phone_types = require("./node-backend/model/phone_types");
console.log('DB CONNECT is: ', dbconfig);
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(cors());
app.use(corsOptions);
// Static directory path
app.use(
express.static(path.join(__dirname, "/"))
);
// API root
app.use("/api/forms", noderoutes);
app.use("/api/phonetypes", phonetyperoute);
app.use("/api/branchesofsvc", branchesofservice);
// PORT
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log("Listening on port number: " + port);
});
// 404 Handler
app.use((req, res, next) => {
next(createError(404));
});
// Base Route
app.get("/", (req, res) => {
res.send("invaild endpoint");
});
app.get("*", (req, res) => {
res.sendFile(
path.join(__dirname, "index.html")
);
});
// THIS IS WHAT I'm trying to call.
app.get('/allphonetypes', (req,res) => {
res.json(phone_types);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
NEXT the DBConn.js is working and here's that.
This is dbconn.js
const sql = require("mssql");
const env = require("../../environment.js")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);
sql.connect(config).then((dbConn) => {
console.log("connected db-conn");
// THIS TEST to my stored proc WORKS FINE and produced 242 records
let query = "exec " + env.STOREDPROCS.GET.ALLCOUNTRIES;
dbConn.query(query, (err, recordset) => {
if (err) {
console.log("Error getting data from Stored Proc: ", err);
sql.close();
}
if (recordset) {
console.log("RESULTS: ", recordset);
} else {
console.log("NO RECORDS RETURNED for ", env.STOREDPROCS.GET.ALLCOUNTRIES);
}
sql.close();
});
}).catch((err) => {
console.log("error", err);
});
This is phone_types.js (the MODEL)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let PhoneTypes = new Schema({
phonetypeid: {
type: Number
},
phonetypename: {
name: String
}
}, {
collection: 'phoneTypes'
})
module.exports = mongoose.model('PhoneTypes', PhoneTypes)
All that should come back from the DB is ID (1 - 3), and HOME, CELL, WORK
And finally, phoneTypeRoutes.js
const express = require("express");
const app = express();
const phoneTypeRoute = express.Router();
const sql = require("mssql");
const PHONE_TYPES = require("../../model/phone_types");
const env = require("../../../environment")
require("msnodesqlv8");
// ConnStr using ODBC
const config = {
connectionString: "Dsn=" + env.VAFORMS.DSN.ACCRED + ";Driver=" + env.VAFORMS.DRIVER + ";Host=" + env.VAFORMS.HOST.LOCAL + ";Database=" + env.VAFORMS.DBNAME.ACCRED + ";trusted_connection=" + env.VAFORMS.OPTIONS.trustedConnection + ";"
};
const dbConn = new sql.ConnectionPool(config);
let query;
query = env.STOREDPROCS.GET.PHONETYPES;
sql.connect(config).then((dbConn) => {
console.log("connected for phonetypes");
}).catch((err) => {
console.log("error", err);
});
// **Get all PhoneTypes NOTE: THIS IS ALL I'm trying for right now...**
phoneTypeRoute.route("/allphonetypes").get((req, res) => {
PHONE_TYPES.find((error, data) => {
dbConn.query(query, (err, recordset) => {
if (data) {
phonetypes.push(recordset);
console.log("RESULTS: ", recordset);
res.send(res.json(recordset));
} else {
console.log("NO RECORDS RETURNED for PHONE TYPES.", error);
return next(err);
}
sql.close();
});
});
});
// Get A specific PHONETYPE
phoneTypeRoute.route("/read-phonetype/:id").get((req, res) => {
PHONE_TYPES.findById(req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});
// ADD PHONE TYPE
phoneTypeRoute.route("/add-phonetype").post((req, res, next) => {
PHONE_TYPES.create(req.body, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
});
});
// Update PHONETYPE
phoneTypeRoute.route("/update-phonetype/:id").put((req, res, next) => {
PHONE_TYPES.findByIdAndUpdate(req.params.id, {
$set: req.body
}, (error, data) => {
if (error) {
console.log(error);
return next(error);
} else {
res.json(data);
console.log("PHONE TYPE updated successfully!");
}
});
});
// Delete PHONETYPE
phoneTypeRoute.route("/delete-phonetype/:id").delete((req, res, next) => {
PHONE_TYPES.findByIdAndRemove(req.params.id, (error, data) => {
if (error) {
return next(error);
} else {
console.log("PHONE TYPE deleted successfully!");
res.status(200).json({msg: data});
}
});
});
module.exports = phoneTypeRoute;
Now the call from Angular
This is crud.service.ts
import { Injectable } from '@angular/core';
import { Form21 } from './forms';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
} from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root',
})
export class CrudService {
// Node/Express API
REST_API: string = 'localhost:8000/api';
// Http Header
httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
constructor(
private httpClient: HttpClient
) { }
...
// GET PHONE TYPES
getPhoneTypes() {
console.log('PHONETYPES: ', this.REST_API + '/allphonetypes');
return this.httpClient.get(this.REST_API + '/allphonetypes');
}
...
// Error
handleError(error: HttpErrorResponse): Observable<VAForm21> {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Handle client error
errorMessage = error.error.message;
} else {
// Handle server error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(() => {
errorMessage;
});
}
}
What I'm getting is NOT FOUND in the NODE terminal and in the browser. Angular is hitting NODE but I get nothing.
This is firing the URL by itself. It results in the same error in my app
Request URL: http://localhost:8000/api/allphonetypes
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:8000
Referrer Policy: strict-origin-when-cross-origin
Finally, in PREVIEW and RESPONSE this is what I get Not Found
It's a routing path problem but I can't seem to find out where.
Thank you